Skip to main content
 首页 » 编程设计

python之在同一页上打印两次的文本

2025年02月15日14落叶无声

我生成的 pdf 有问题,生成的 pdf 文件有 4 页,我使用现有的 pdf 有两页。我必须使用 pyPD2 和 reportlab 编写一些文本。

当我使用getPage() 方法时,我想在合并之前制作一个页面副本,但由于某些原因它使用相同的页面,我的文本被打印了好几次。

我怎样才能避免这种情况?

我的代码:

packet = io.BytesIO() 
can = canvas.Canvas(packet) 
can.drawString(0,0, "Print on page 1") 
can.showPage() 
can.drawString(200,200, "Print on page 2") 
can.showPage() 
can.drawString(0,0, "Print on page 3") 
can.showPage() 
can.drawString(200,200, "Print on page 4") 
can.save() 
 
new_pdf = PdfFileReader(packet) 
 
path_of_two_page_pdf = 'overview.pdf' 
existing_pdf = PdfFileReader(file(path_of_two_page_pdf, "rb")) 
 
output = PdfFileWriter() 
for pi in range(4): 
    page = existing_pdf.getPage(pi % 2) 
    page.mergePage(new_pdf.getPage(pi)) 
    output.addPage(page) 
 
outputStream = file("NEW_PDF.pdf", "wb") 
output.write(outputStream) 
outputStream.close() 

请您参考如下方法:

问题是 getPage() 实际上返回了指向页面的指针,而不是一个全新的页面。因此,当应用 mergePage() 时,它会将其合并到现有的 pdf 中。

最简单的解决方法是先创建一个空白页面,然后用它来合并其他页面,如下所示:

for pi in range(2*2): 
    # By doing this we will always create a blank page with the same size as the last page of the existing_pdf 
    new_page = PageObject.createBlankPage(pdf=existing_pdf) 
 
    # Merge the pages onto the blank page 
    new_page.mergePage(existing_pdf.getPage(pi % 2)) 
    new_page.mergePage(new_pdf.getPage(pi)) 
 
    # Add the new page to the output 
    output.addPage(new_page) 

请注意,除了使用 createBlankPage 创建一个完全独立的空白页之外,您还可以使用 output.addBlankPage 但这需要手动设置页面大小,这可能并不理想.因此使用 createBlankPage 的 pdf 关键字,这会将页面大小设置为提供的 pdf 的最后一页。