ホームページ  >  記事  >  バックエンド開発  >  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 システムの両方と互換性のあるモジュールを特定することが重要です。

推奨モジュール:

さまざまなオプションを検討した結果、2 つの適切なモジュールは PyPDF2 と 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>

これらのコード例は、既存の PDF ファイルの最初のページにテキスト「Hello world」を追加し、結果を新しい PDF ファイルに保存します。テキストと位置はそれに応じてカスタマイズできます。

以上がPython を使用して既存の PDF にテキストを追加する方法の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

声明:
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。