Python 3 pdfrw Library Tutorial to Add Watermark to PDF Document Full Project For Beginners



Welcome folks today in this blog post we will be adding the watermark to pdf document in python using pdfrw library. All the full source code of the application is shown below.




Get Started




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



pip install pdfrw



After installing this library you need to make an file and copy paste the following code



#!/usr/bin/env python

Simple example of watermarking using form xobjects (pdfrw).
usage: [-u] my.pdf single_page.pdf
Creates, with every page overlaid with
first page from single_page.pdf.  If -u is selected, watermark
will be placed underneath page (painted first).
NOTE 1: This program assumes that all pages (including the watermark
        page) are the same size.  For other possibilities, see
        the example.
NOTE 2: At one point, this example was extremely complicated, with
        multiple options.  That only led to errors in implementation,
        so it has been re-simplified in order to show basic principles
        of the library operation and to match the other examples better.

import sys
import os

from pdfrw import PdfReader, PdfWriter, PageMerge

argv = sys.argv[1:]
underneath = '-u' in argv
if underneath:
    del argv[argv.index('-u')]
inpfn, wmarkfn = argv
outfn = 'watermark.' + os.path.basename(inpfn)
wmark = PageMerge().add(PdfReader(wmarkfn).pages[0])[0]
trailer = PdfReader(inpfn)
for page in trailer.pages:
    PageMerge(page).add(wmark, prepend=underneath).render()
PdfWriter(outfn, trailer=trailer).write()

Leave a Reply