Home >Backend Development >Python Tutorial >How to Overlay Additional Text onto Existing PDFs using Python?

How to Overlay Additional Text onto Existing PDFs using Python?

Barbara Streisand
Barbara StreisandOriginal
2024-10-22 14:41:23357browse

How to Overlay Additional Text onto Existing PDFs using Python?

Adding Text to Existing PDFs with Python

PyPDF and ReportLab are capable of creating and manipulating PDFs, but they fall short when it comes to editing existing ones. Let's explore an alternative approach.

To overlay additional text onto an existing PDF, Python offers a combination of the PyPDF2 and reportlab modules. PyPDF2 provides the functionality to extract pages from the original document, while reportlab allows us to generate new text content.

Here's a detailed example in 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>

For Python 3.x, use this similar approach:

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

The above is the detailed content of How to Overlay Additional Text onto Existing PDFs using Python?. 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