-
-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathaddWatermarkPDF.py
47 lines (37 loc) · 1.45 KB
/
addWatermarkPDF.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
"""
addWatermarkPDF.py - Add watermark to every page of a PDF document
Usage: run "python3 addWatermarkPDF.py" and enter the filenames of
the PDF to be watermarked and the watermark PDF.
"""
from os import path
import sys
import PyPDF3
# PDF filenames
baseFileName = input('Enter the name of the PDF file to be watermarked:\n')
baseFileName = path.abspath(baseFileName)
watermarkName = input('Enter the name of watermark PDF:\n')
watermarkName = path.abspath(watermarkName)
# Check if entered filenames are valid
if not path.exists(baseFileName) or baseFileName[-4:].lower() != '.pdf':
print(f'The filename {baseFileName} is not a PDF.')
sys.exit()
elif not path.exists(watermarkName) or watermarkName[-4:].lower() != '.pdf':
print(f'The filename {watermarkName} is not a PDF.')
sys.exit()
else:
print('Adding Watermark...')
baseFile = open(baseFileName, 'rb')
pdfReader = PyPDF3.PdfFileReader(baseFile)
pdfWatermarkReader = PyPDF3.PdfFileReader(open(watermarkName, 'rb'))
pdfWriter = PyPDF3.PdfFileWriter()
# Merge watermark to each page of PDF
for pageNum in range(pdfReader.numPages):
pageObj = pdfReader.getPage(pageNum)
pageObj.mergePage(pdfWatermarkReader.getPage(0))
pdfWriter.addPage(pageObj)
# Save the resulting PDF to a file
markedPdfFile = open('watermarked' + path.basename(baseFileName), 'wb')
pdfWriter.write(markedPdfFile)
baseFile.close()
markedPdfFile.close()
print(f'Watermarked file saved as watermarked{path.basename(baseFileName)}')