【问题标题】:Writing text over a PDF in python3在 python3 中在 PDF 上写入文本
【发布时间】:2018-05-14 08:53:44
【问题描述】:

我正在尝试在某个位置将一些字符串写入 PDF 文件。 我找到了一种方法并像这样实现它:

from PyPDF2 import PdfFileWriter, PdfFileReader
import io
from reportlab.pdfgen import canvas
from reportlab.lib.pagesizes import letter

packet = io.StringIO()
# create a new PDF with Reportlab
can = canvas.Canvas(packet, pagesize=letter)
can.drawString(10, 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("original.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("destination.pdf", "wb")
output.write(outputStream)
outputStream.close()

它在can.save() 行给我一个错误

错误:

File "/home/corleone/miniconda3/lib/python3.6/site-packages/reportlab/pdfgen/canvas.py", line 1237, in save
    self._doc.SaveToFile(self._filename, self)
  File "/home/corleone/miniconda3/lib/python3.6/site-packages/reportlab/pdfbase/pdfdoc.py", line 224, in SaveToFile
    f.write(data)
TypeError: string argument expected, got 'bytes'

已在互联网上的很多地方阅读过。到处都找到了同样的方法。是不是方法不对。我错过了什么吗?

【问题讨论】:

    标签: python python-3.x pdf canvas pypdf2


    【解决方案1】:

    发现我只需要使用BytesIO 而不是StringsIO

    还有open() 而不是file(),因为我使用的是Python3。

    这是工作脚本:

    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.setFont('Helvetica-Bold', 24)
    can.drawString(10, 100, "Hello world")
    can.showPage()
    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("original.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 = open("destination.pdf", "wb")
    output.write(outputStream)
    outputStream.close()
    

    【讨论】:

      猜你喜欢
      • 2012-05-20
      • 1970-01-01
      • 2016-08-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-10-12
      • 1970-01-01
      • 2013-10-10
      相关资源
      最近更新 更多