使用Python 將文字加入現有PDF
問題:
問題:如何合併附加文字使用Python 將文字轉換為現有PDF 檔案?此任務需要哪些外部函式庫?
答案:要實現此目的,可以結合使用 PyPDF2 和 ReportLab 庫,同時支援 Windows 和 Linux相容性。具體方法如下:
<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() packet.seek(0) new_pdf = PdfFileReader(packet) existing_pdf = PdfFileReader(file("original.pdf", "rb")) output = PdfFileWriter() page = existing_pdf.getPage(0) page.mergePage(new_pdf.getPage(0)) output.addPage(page) outputStream = file("destination.pdf", "wb") output.write(outputStream) outputStream.close()</code>
Python 2.7 例:
<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() packet.seek(0) new_pdf = PdfFileReader(packet) existing_pdf = PdfFileReader(open("original.pdf", "rb")) output = PdfFileWriter() page = existing_pdf.pages[0] page.merge_page(new_pdf.pages[0]) output.add_page(page) output_stream = open("destination.pdf", "wb") output.write(output_stream) output_stream.close()</code>
Python 3.x 範例:
Python 3.x範例:Python 3.x範例:Python 3.x範例:Python 3.x範例:Python 3.x範例:透過利用這些函式庫,您可以輕鬆地將文字新增至Windows 和Linux 平台上的Python 2.7 和Python 3.x 環境中的現有PDF 文件中。以上是如何使用 Python 將文字新增至現有 PDF:庫要求和程式碼實現的詳細內容。更多資訊請關注PHP中文網其他相關文章!