如何使用canvas向pdf添加另一个页面?

x9ybnkn6  于 2021-07-13  发布在  Java
关注(0)|答案(1)|浏览(404)

我开发了一个基于电子表格的应用程序,列出一些客户的未结费用,并将其保存在pdf中。代码工作得很好,但是当保存到pdf时,如果打开的费用非常大,页面的内容会被剪切,但不会添加另一个页面。
代码如下:

  1. # !/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. from __future__ import unicode_literals
  4. from tkinter import *
  5. from tkinter import ttk
  6. from tkinter import messagebox
  7. from reportlab.pdfgen import canvas
  8. from reportlab.lib.pagesizes import letter
  9. import openpyxl
  10. import os
  11. pastaApp = os.path.dirname(__file__)
  12. def createPDF():
  13. # Opens the spreadsheet and obtains the status of the last payment.
  14. wb = openpyxl.load_workbook('C:/temp/cobranca.xlsx')
  15. sheet = wb['Sheet1']
  16. lastCol = sheet.max_column
  17. # Checks the payment status of each customer.
  18. unpaidMembers = {}
  19. clients = []
  20. months = []
  21. emails = []
  22. for r in range(2, sheet.max_row + 1):
  23. for c in range(3, lastCol + 1):
  24. payment = sheet.cell(row=r, column=c).value
  25. if payment != 'ok':
  26. client = sheet.cell(row=r, column=1).value
  27. email = sheet.cell(row=r, column=2).value
  28. month = sheet.cell(row=1, column=c).value
  29. clients.append(client)
  30. months.append(month)
  31. emails.append(email)
  32. unpaidMembers[client] = email
  33. #print('Line:', r, 'Column:', c, 'Client:', client, 'Email:', email, 'Month:', month)
  34. print('dictionary created successfully')
  35. cnv = canvas.Canvas(pastaApp+"\\test.pdf", pagesize=letter)
  36. cnv.drawString(10, 800, "Open Fee")
  37. cnv.drawString(130, 800, " - Client/Month/E-mail")
  38. y = 780
  39. for client, month, email in zip(clients, months, emails):
  40. cnv.drawString(10, y, client)
  41. cnv.drawString(170, y, month)
  42. cnv.drawString(350, y, email)
  43. y -= 20
  44. cnv.save()
  45. root = Tk()
  46. root.title("Create PDF")
  47. btn_createPDF = Button(root, text="Check", command=createPDF)
  48. btn_createPDF.pack(side="left", padx=10)
  49. root.mainloop()

电子表格模型used:https网址:prnt.sc/125pi9y

pw136qt2

pw136qt21#

你需要检查 y 在你的 for 循环。如果它低于36(半英寸边距),那么打电话给 cnv.showPage() ,重置 y ,并打印新的页眉。

  1. cnv = canvas.Canvas(pastaApp+"\\test.pdf", pagesize=letter)
  2. cnv.drawString(10, 800, "Open Fee")
  3. cnv.drawString(130, 800, " - Client/Month/E-mail")
  4. y = 780
  5. for client, month, email in zip(clients, months, emails):
  6. cnv.drawString(10, y, client)
  7. cnv.drawString(170, y, month)
  8. cnv.drawString(350, y, email)
  9. y -= 20
  10. if y < 36:
  11. cnv.showPage()
  12. cnv.drawString(10, 800, "Open Fee")
  13. cnv.drawString(130, 800, " - Client/Month/E-mail")
  14. y = 780

将页眉打印机分离为一个单独的函数留给读者作为练习。

展开查看全部

相关问题