Python 3 Script to Add a Watermark or Stamp to PDF Documents Using PyPDF4 Library Full Project For Beginners


Welcome folks today in this blog post we will be adding a watermark or stamp to pdf documents using pypdf4 library in python 3.All the full source code of the application is shown below.




Get Started




In order to get started you need to install the below libraries using the pip command as shown below



pip install pypdf4



After installing this libraries make an file and copy paste the following code



# compatible with Python versions 2.6, 2.7,
# and 3.2 - 3.5. (pip3 install pypdf4)
from PyPDF4 import PdfFileWriter, PdfFileReader
import PyPDF4


def put_watermark(input_pdf, output_pdf, watermark):
    # reads the watermark pdf file through
    # PdfFileReader
    watermark_instance = PdfFileReader(watermark)
    # fetches the respective page of
    # watermark(1st page)
    watermark_page = watermark_instance.getPage(0)
    # reads the input pdf file
    pdf_reader = PdfFileReader(input_pdf)
    # It creates a pdf writer object for the
    # output file
    pdf_writer = PdfFileWriter()

    # iterates through the original pdf to
    # merge watermarks
    for page in range(pdf_reader.getNumPages()):
        page = pdf_reader.getPage(page)
        # will overlay the watermark_page on top
        # of the current page.
        # add that newly merged page to the
        # pdf_writer object.

    with open(output_pdf, 'wb') as out:
        # writes to the respective output_pdf provided

if __name__ == "__main__":
        input_pdf='GFG.pdf', # the original pdf
        output_pdf='watermark_added1.pdf', # the modified pdf with watermark
        watermark='geeks.pdf' # the watermark to be provided

Leave a Reply