首頁  >  文章  >  後端開發  >  如何使用 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