使用 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中文网其他相关文章!