DEV Community

Cover image for Add watermark to your PDF file with Python
Stokry
Stokry

Posted on

Add watermark to your PDF file with Python

Add watermark to your PDF file with Python

Today I will show you how you can simply add a watermark to all pages within a PDF file.
I'll use PyPDF2

A Pure-Python library built as a PDF toolkit. It is capable of:

  • extracting document information (title, author, …)
  • splitting documents page by page
  • merging documents page by page
  • cropping pages
  • merging multiple pages into a single page
  • encrypting and decrypting PDF files
  • and more!

By being Pure-Python, it should run on any Python platform without any dependencies on external libraries. It can also work entirely on StringIO objects rather than file streams, allowing for PDF manipulation in memory. It is therefore a useful tool for websites that manage or manipulate PDFs.

Let's jump to the code

from PyPDF2 import PdfFileMerger, PdfFileReader, PdfFileWriter

pdf_file = r'C:\Users\Stokry\Desktop\python\pdf\test1.pdf'
watermark = r'C:\Users\Stokry\Desktop\python\pdf\logopdf.pdf'
merged = r'C:\Users\Stokry\Desktop\python\pdf\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)
Enter fullscreen mode Exit fullscreen mode

The code will put a watermark on all pages within the PDF.

That's all. Keep coding.

Discussion (3)

Collapse
pradeepradyumna profile image
Pradeep Pradyumna

Good one!

Collapse
stokry profile image
Stokry Author

Thanks😀

Collapse
dev_emmy profile image
nshimiye_emmy

thanks