How to Add Watermark to a PDF File Using Python

Hey there everyone, Today we are going to learn how to add a watermark to a pdf file using Python.
We will be using the PyPDF2 library of Python which is capable of merging two pdf files.

Add Watermark to a PDF file in Python

We have two pdf files one of which contains only text(can also have images) and the other one contains the watermark to be added.
The basic idea behind this would be merging the two pdf files.

Our watermark file “watermark.pdf” is:
watermark.pdf

Screenshot of the file is below:

add watermark to pdf file in Python

We will be adding the above-mentioned watermark to the pdf file “doc.pdf”:
doc.pdf

After merging the above two pdf files we will get our output file containing the contents of both “watermark.pdf” and “doc.pdf”.

LET’S DISCUSS THE STEPS INVOLVED :

  • Importing the PyPDF2 module.
    import PyPDF2
  • Storing the contents of the pdf file and the watermark file.
    pdf_file = "doc.pdf"
    watermark = "watermark.pdf"
    merged_file = "merged.pdf"
  • Open and Read the pdf file and the watermark file.
    input_file = open(pdf_file,'rb')
    input_pdf = PyPDF2.PdfFileReader(pdf_file)
    
    watermark_file = open(watermark,'rb')
    watermark_pdf = PyPDF2.PdfFileReader(watermark_file)
  • Accessing the pages of the pdf file and the watermark file to be merged, Index 0 is used to access the first page.
    pdf_page = input_pdf.getPage(0)
    
    watermark_page = watermark_pdf.getPage(0)
  • Merging the pages.
    pdf_page.mergePage(watermark_page)
  • Saving our file in the output.
    output = PyPDF2.PdfFileWriter()
    output.addPage(pdf_page)
  • The final pdf file after adding the watermark is stored in merged_file.
    merged_file = open(merged_file,'wb')
    output.write(merged_file)
  • closing the files.
    merged_file.close()
    watermark_file.close()
    input_file.close()

     

Python program to add watermark to pdf

import PyPDF2

pdf_file = "doc.pdf"

watermark = "watermark.pdf"

merged_file = "merged.pdf"

input_file = open(pdf_file,'rb')
input_pdf = PyPDF2.PdfFileReader(pdf_file)

watermark_file = open(watermark,'rb')
watermark_pdf = PyPDF2.PdfFileReader(watermark_file)

pdf_page = input_pdf.getPage(0)

watermark_page = watermark_pdf.getPage(0)

pdf_page.mergePage(watermark_page)

output = PyPDF2.PdfFileWriter()

output.addPage(pdf_page)

merged_file = open(merged_file,'wb')
output.write(merged_file)

merged_file.close()
watermark_file.close()
input_file.close()

After the successful execution of this code, we will have our output pdf file named “merged.pdf”.
merged.pdf

Screenshot:

watermarking to pdf

4 responses to “How to Add Watermark to a PDF File Using Python”

  1. Shyok Mutsuddi says:

    Nice explaination!

  2. Sulaiman says:

    any idea how to make watermark background transparent?

Leave a Reply

Your email address will not be published. Required fields are marked *