Home  >  Article  >  Backend Development  >  How to Add Text to Existing PDFs Using Python: Library Requirements and Code Implementation

How to Add Text to Existing PDFs Using Python: Library Requirements and Code Implementation

DDD
DDDOriginal
2024-10-22 16:50:02406browse

How to Add Text to Existing PDFs Using Python: Library Requirements and Code Implementation

Adding Text to Existing PDFs with Python

Question:

How can I incorporate additional text into an existing PDF file using Python? Which external libraries are necessary for this task?

Answer:

To achieve this, a combination of PyPDF2 and ReportLab libraries can be employed, allowing for both Windows and Linux compatibility. Here's how:

Python 2.7 Example:

<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 3.x Example:

<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>

By utilizing these libraries, you can effortlessly add text to existing PDF documents in both Python 2.7 and Python 3.x environments on both Windows and Linux platforms.

The above is the detailed content of How to Add Text to Existing PDFs Using Python: Library Requirements and Code Implementation. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn