python - 在 python3 中通过 PDF 写入文本

标签 python python-3.x pdf canvas pypdf

我正在尝试在某个位置将一些字符串写入 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'

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

最佳答案

发现我只需要使用 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()

关于python - 在 python3 中通过 PDF 写入文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47573258/

相关文章:

python - Beautifulsoup for row 循环只运行一次?

python - 正则表达式 match() 无法捕获 python 中的简单模式

iphone - 创建类似于 iBook 或 Stanza 应用程序的 ePub 阅读器的最佳方法

python - 基于索引对DataFrame进行分箱

node.js - 从 API 检索的 PDF 中的空白页

php - 将页面保存为 PDF 或 HTML,但包含所有条目

python - 重新启动 Pygame?

python - 比较数据帧字典中的列

python - 如何对 pandas 中的字母数字字段进行排序?

python - 在 macOS 上将 Python 版本升级到 3.9 现在会为某些文件读取代码提供 “variable not defined” 错误