使用Python 將文字新增至現有PDF
PyPDF 和ReportLab 能夠建立和操作PDF,但在涉及編輯現有的。讓我們探索另一種方法。
為了將附加文字疊加到現有 PDF 上,Python 提供了 PyPDF2 和 reportlab 模組的組合。 PyPDF2 提供了從原始文件中提取頁面的功能,而 reportlab 允許我們產生新的文字內容。
這是 Python 2.7 中的詳細範例:
<code class="python">import StringIO from pyPdf import PdfFileWriter, PdfFileReader from reportlab.pdfgen import canvas from reportlab.lib.pagesizes import letter # Create a new PDF with the additional text buffer = StringIO.StringIO() canvas = canvas.Canvas(buffer, pagesize=letter) canvas.drawString(10, 100, "Hello world") canvas.save() new_pdf = PdfFileReader(buffer) buffer.seek(0) # Read the existing PDF existing_pdf = PdfFileReader(open("original.pdf", "rb")) output = PdfFileWriter() # Merge the new text onto the existing pages page = existing_pdf.getPage(0) page.mergePage(new_pdf.getPage(0)) output.addPage(page) # Save the updated PDF outputStream = open("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 buffer = io.BytesIO() canvas = canvas.Canvas(buffer, pagesize=letter) canvas.drawString(10, 100, "Hello world") canvas.save() new_pdf = PdfFileReader(buffer) buffer.seek(0) 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 將附加文字疊加到現有 PDF 上?的詳細內容。更多資訊請關注PHP中文網其他相關文章!