[Python]Merge & Watermark PDF

Nikhil Narayanan
2 min readApr 14, 2020

--

When we search in web, we get a lot of resources where we are just uploading our pdf files and getting it merged together. What’s the fun in that? the fun part comes in when we code our program that merges our pdf file.

Where should I start?.

Luckily we have Python, Python has a great community of developers, who are contributing their projects in PyPI (Python Package Index). We need to search through and find the module of our needs, if not, then we can contribute our code to this community also.

Today, we will discuss about a module called PyPDF2. This module has great classes which helps to achieve many super pdf functions. Lets see how they are done

Install Package

If you don’t have this module installed, you can install it using pip

How this works

PyPDF has 3 main class for reading, writing and merging. These classes have many methods which help us perform lot many operations in pdf. We can. create a reader object which can read pdf file and to operate on it, this module provides us a Page object, which makes our life easier for accessing each page out of the entire pdf file.

Another thing, which we need to remember is, pdf files needs to be opened as binary. Let see how we can create a merge function

We can just merge our pdf files using just 4 lines of python code.

How watermark works

To watermark our pdf, we need to have a pdf which have the contents of watermark and this pdf is merged with the pdf, which needs to be watermarked. This is how it works in PyPDF. Let see how it is done in the code.

This is as simple as this. Here we are using the classes which we discussed at the beginning section of this article.

To help you all do the merge and watermark your pdf files, I am sharing my Python program, which does following,

  • Provides option to give pdf files one by one and merge them with a name
  • Just point out the directory, where the pdf files are, rest it takes care
  • Pass in the pdf and the watermark pdf and will do watermarking for you

This is the complete program,

Example: Executing above program,

Hope you like this article. Please share your comments.

Keep Coding..!!

--

--

Nikhil Narayanan
Nikhil Narayanan

Written by Nikhil Narayanan

DevOps Engineer | Python Developer | Machine Learning | Artificial intelligence Enthusiast

No responses yet