from PyPDF2 import PdfFileReader, PdfFileWriter
from reportlab.pdfgen import canvas
def fill_pdf(template_path, output_path, data):
# Read the existing PDF
existing_pdf = PdfFileReader(template_path)
# Create a new PDF with the same size and layout
new_pdf = PdfFileWriter()
# Add the pages from the old into the new PDF
for page in existing_pdf.pages:
new_pdf.addPage(page)
# Loop through the data
for index, (key, value) in enumerate(data.items()):
# Loop through the pages of the PDF
for page in new_pdf.pages:
# Extract the content stream
content = page['/Resources']['/Content'].getObject()
# Loop through the content stream lines
for i, operator, operands in content:
# If the content line contains the key
if key in operands[0]:
# Replace the key with the value
operands[0] = key + " " + value
# Create a new file and write the new PDF to it
with open(output_path, 'wb') as new_file:
new_pdf.write(new_file)
# Call the function with the template PDF, the output PDF and the data
fill_pdf('template.pdf', 'output.pdf', {'Name': 'John Doe', 'Address': '123 Main St', 'City': 'Springfield', 'State': 'OR', 'Zip': '97477'})
This script will take a template.pdf file, fill in the fields with the data from the dictionary, and save the filled-in form to output.pdf.
Also, this is a very basic solution and may not work for all PDFs, especially those with complex structures or encryption. For more complex PDF processing, you might need to use a more advanced library or tool.