首页  >  文章  >  后端开发  >  如何使用 Python 将文本添加到现有 PDF?

如何使用 Python 将文本添加到现有 PDF?

Patricia Arquette
Patricia Arquette原创
2024-10-22 14:56:02690浏览

How to Add Text to Existing PDFs Using Python?

使用 Python 将文本添加到现有 PDF

背景:

通常,您可能需要向现有 PDF 文档添加其他文本。幸运的是,Python 提供了几个可以简化此任务的模块。然而,识别与 Windows 和 Linux 系统兼容的模块很重要。

推荐模块:

在考虑各种选项后,两个合适的模块是 PyPDF2 和PyPDF。这些模块提供高级别的功能和跨平台支持。

代码示例:

以下是 Python 2.7 和 Python 3 的代码示例。 x:

Python 2.7:

<code class="python">from pyPdf import PdfFileWriter, PdfFileReader
import StringIO
from reportlab.pdfgen import canvas
from reportlab.lib.pagesizes import letter

packet = StringIO.StringIO()
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)

# Create a new PDF with Reportlab
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()</code>

Python 3.x:

<code class="python">from PyPDF2 import PdfFileWriter, PdfFileReader
import io
from reportlab.pdfgen import canvas
from reportlab.lib.pagesizes import letter

packet = io.BytesIO()
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)

# Create a new PDF with Reportlab
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.pages[0]
page.merge_page(new_pdf.pages[0])
output.addPage(page)
# Finally, write "output" to a real file
output_stream = open("destination.pdf", "wb")
output.write(output_stream)
output_stream.close()</code>

这些代码示例会将文本“Hello world”添加到现有 PDF 文件的第一页,并将结果保存到新的 PDF 文件中。您可以相应地自定义文本和位置。

以上是如何使用 Python 将文本添加到现有 PDF?的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn