通常,您可能需要向现有 PDF 文档添加其他文本。幸运的是,Python 提供了几个可以简化此任务的模块。然而,识别与 Windows 和 Linux 系统兼容的模块很重要。
在考虑各种选项后,两个合适的模块是 PyPDF2 和PyPDF。这些模块提供高级别的功能和跨平台支持。
以下是 Python 2.7 和 Python 3 的代码示例。 x:
<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>
<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中文网其他相关文章!