from PyPDF2 import PdfFileWriter, PdfFileReader
import io
from reportlab.pdfgen import canvas
from reportlab.lib.pagesizes import letter
packet = io.BytesIO()
# create a new PDF with Reportlab
can = canvas.Canvas(packet, pagesize=letter)
can.drawString(100, 100, "Hello world")
can.save()
# move to the beginning of the StringIO buffer
packet.seek(0)
new_pdf = PdfFileReader(packet)
# read your existing PDF
existing_pdf = PdfFileReader(open("mypdf.pdf", "rb"))
output = PdfFileWriter()
# add the "watermark" (which is the new pdf) on the existing page
page = existing_pdf.getPage(0)
page2 = new_pdf.getPage(0)
page.mergePage(page2)
output.addPage(page)
# finally, write "output" to a real file
outputStream = open("newpdf.pdf", "wb")
output.write(outputStream)
outputStream.close()
from pyPdf import PdfFileWriter, PdfFileReader
import StringIO
from reportlab.pdfgen import canvas
from reportlab.lib.pagesizes import letter
packet = StringIO.StringIO()
# create a new PDF with Reportlab
can = canvas.Canvas(packet, pagesize=letter)
can.drawString(100,100, "Hello world")
can.save()
#move to the beginning of the StringIO buffer
packet.seek(0)
new_pdf = PdfFileReader(packet)
# read your existing PDF
existing_pdf = PdfFileReader(file("mypdf.pdf", "rb"))
output = PdfFileWriter()
# add the "watermark" (which is the new pdf) on the existing page
page = existing_pdf.getPage(0)
page.mergePage(new_pdf.getPage(0))
output.addPage(page)
# finally, write "output" to a real file
outputStream = file("/home/joe/newpdf.pdf", "wb")
output.write(outputStream)
outputStream.close()
你应该看看Add text to Existing PDF using Python和Python as PDF Editing and Processing Framework。这些会指引你正确的方向。
如果按照问题中的建议执行,当导出回
.pdf
时,它实际上只是嵌入在.pdf
中的图像文件,而不是文本。我刚刚尝试了上面的解决方案,但在Python3中运行时遇到了一些麻烦。所以,我想分享我的修改。修改后的代码如下:
现在page.mergePage抛出一个错误。结果是pypdf2中的一个移植错误。请参考此问题以获取解决方案:Porting to Python3: PyPDF2 mergePage() gives TypeError
在四处寻找之后,我终于找到了解决办法: 结果发现this毕竟是正确的方法。 但是,我觉得这不够冗长。 这张海报似乎是从here(相同的变量名等)中摘取的。
想法:用Reportlab创建新的空白PDF,它只包含一个文本字符串。 然后使用pyPdf将其合并/添加为水印。
希望这能帮助别人。
相关问题 更多 >
编程相关推荐