Skip to content
Advertisement

How to add watermark in all pages of PDF files with python?

I’m try to adding watermark to every pages of my PDF file.My PDF files have 58 pages but my output file has get only last page in my PDF file.

My PDF file have 59 pages.

This's my PDF Output files.

This’s my code:

from PyPDF2 import PdfFileReader, PdfFileWriter

watermark_pdf = PdfFileReader("watermark.pdf")
watermark_page = watermark_pdf.getPage(0)
reader = PdfFileReader("original_document.pdf")

for page in reader.pages:
    page.mergePage(watermark_page)
    output = PdfFileWriter()
    output.addPage(page)
    with open("watermarked_document.pdf", "wb") as fp:
        output.write(fp)

Please tell me how to add watermark all pages.

Advertisement

Answer

You’re rewriting your “merged” file for each page.

Try something like

from PyPDF2 import PdfFileMerger, PdfFileReader, PdfFileWriter

pdf_file = "C:/Users/11359023/Desktop/deepfake_vee.pdf"
watermark = "C:/Users/11359023/Desktop/simple.pdf"
merged = "C:/Users/11359023/Desktop/merged.pdf"

with open(pdf_file, "rb") as input_file, open(watermark, "rb") as watermark_file:
    input_pdf = PdfFileReader(input_file)
    watermark_pdf = PdfFileReader(watermark_file)
    watermark_page = watermark_pdf.getPage(0)

    output = PdfFileWriter()

    for i in range(input_pdf.getNumPages()):
        pdf_page = input_pdf.getPage(i)
        pdf_page.mergePage(watermark_page)
        output.addPage(pdf_page)

    with open(merged, "wb") as merged_file:
        output.write(merged_file)

instead.

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement