DEV Community

Cover image for Watermark pdf
bluepaperbirds
bluepaperbirds

Posted on

Watermark pdf

You can do a lot of neat things using the Python programming language. Using Python you can easily watermark a pdf. You can use a module called python3-fitz which uses MuPDF underneath (install this too)

If you don't know the Python programming language, I recommend this tutorial as a starting point.

You can install both fitz and mupdf using your package manager.

sudo apt install python3-fitz
sudo apt install mupdf
Enter fullscreen mode Exit fullscreen mode

Python watermark

Then you need an input file and an image. Set the position using the fitz.Rect() function.

Load the module like this:

import fitz
Enter fullscreen mode Exit fullscreen mode

Install it using your operating systems package manager. If you use pip, there seem to be some other packages named fitz which are conflicting.

Then open the pdf

doc = fitz.open("input.pdf")
Enter fullscreen mode Exit fullscreen mode

Set the location of your watermark

rect = fitz.Rect(0, 0, 100, 100)
Enter fullscreen mode Exit fullscreen mode

Iterate over the pages and insert the water mark

for page in doc:
    page.insertImage(rect, filename="logo.jpeg")
Enter fullscreen mode Exit fullscreen mode

And save it. The full code:

import fitz
doc = fitz.open("input.pdf")
rect = fitz.Rect(0, 0, 100, 100)

for page in doc:
    page.insertImage(rect, filename="logo.jpeg")

doc.save("output.pdf")
Enter fullscreen mode Exit fullscreen mode

If you run the program it will output a new pdf with the watermark image on top of every page.

Make a backup of your file before you run it. If you want, you can build a GUI around it using something like tkinter or pyqt

Top comments (0)