0

I want to put a stamp on the first page of every pdf file in a specified folder(not to merge all the pdf files in the folder together) using PyPDF2. I want to put a bunch of pdf files in a folder and have them each individually stamped with the simple click of the "Run" button.

I want to go down the list in the folder and merge the first page of each .pdf file with the stamp.pdf (and then Overwrite the original .pdf if possible) then move on to merge the next .pdf with stamp.pdf... and so on.

With the current code below, I have gotten it to merge my stamp.pdf file with the first page of the specified input.pdf file. However, I don't want to have to specify each pdf one by one.

The current code below merges and the stamp is at the bottom left of the page of the output pdf. I am okay with that but not sure if there is a way to specify where the stamp is placed/add text on top of the stamp once merged. I APPRECIATE ANY HELP!

import os
import PyPDF2
import io
from reportlab.pdfgen import canvas
from reportlab.lib.pagesizes import letter

input_file = r'C:\User\Example_User\Desktop\input.pdf'
output_file = r'C:\User\Example_User\Desktop\input_stamped.pdf'
watermark_file = r'C:\User\Example_User\Desktop\stamp.pdf'

with open(input_file, "rb") as filehandle_input:
    # read content of the original file
    pdf = PyPDF2.PdfFileReader(filehandle_input)

    with open(watermark_file, "rb") as filehandle_watermark:
        # read content of the watermark
        watermark = PyPDF2.PdfFileReader(filehandle_watermark)

        # get first page of the original PDF
        first_page = pdf.getPage(0)

        # get first page of the watermark PDF
        first_page_watermark = watermark.getPage(0)

        # merge the two pages
        first_page.mergePage(first_page_watermark)


        # create a pdf writer object for the output file
        pdf_writer = PyPDF2.PdfFileWriter()

        for page in pdf.pages:
            pdf_writer.addPage(page)

        with open(output_file, "wb") as filehandle_output:
            # write the watermarked file to the new file
            pdf_writer.write(filehandle_output)

0 Answers0