Welcome folks today in this blog post we will be adding watermark
to pdf document using pypdf2
library in python. 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 pypdf2
After installing this make an app.py
file and copy paste the following code
app.py
1 2 3 4 5 6 7 |
import PyPDF2 pdf_file = "sample.pdf" watermark = "watermark.pdf" merged_file = "merged.pdf" |
First of all we are declaring all the files which are needed
for this application. So you need to load the watermark.pdf
file which will look like this as shown below
1 2 3 4 5 |
input_file = open(pdf_file,'rb') input_pdf = PyPDF2.PdfFileReader(input_file) watermark_file = open(watermark,'rb') watermark_pdf = PyPDF2.PdfFileReader(watermark_file) |
Now we are opening both the input
pdf file and the watermark
pdf file using the open
method and then we are reading the pdf files
using the PdfFileReader()
method.
1 2 3 4 5 |
pdf_page = input_pdf.getPage(0) watermark_page = watermark_pdf.getPage(0) pdf_page.mergePage(watermark_page) |
Now we are taking the first
page of each of the pdf document
and then we are simply merging it
just to give the impression that the watermark
is added to the input pdf document. We are getting the first page of the pdf document using the getPage()
method. And then we are using the mergePage()
method to merge the pages inside the pdf document.
1 2 3 4 5 6 7 8 9 10 |
output = PyPDF2.PdfFileWriter() output.addPage(pdf_page) merged_file = open(merged_file,'wb') output.write(merged_file) merged_file.close() watermark_file.close() input_file.close() |
And now we are using the PdfFileWriter()
method to write the file and then we are adding the page using the addPage()
method. And then we are opening the resultant pdf file
in write binary mode. And simply saving the file as merged.pdf
in the root directory. And lastly we are closing the file
connections. Now if you open the resultant pdf
file the result will look like this as shown below