python模块推荐【】pypdf2自动添加水印

需求场景

为多个pdf文件自动添加水印。

实战代码

准备文件,创建一页带有水印的pdf文件。

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
48
49
50
51
52
53
54
55
56
# !/usr/bin/python
# Adding a watermark to a single-page PDF

import PyPDF2
from glob import glob


input_file = "example.pdf"
output_file = "example-drafted.pdf"
watermark_file = "draft.pdf"


def addwatermark(inputf,watermark,outf=""):
'''
'''
print("convert the file %s to watermaped file"%inputf)
pdf_writer = PyPDF2.PdfFileWriter()

if not outf:
outf=inputf.replace(".pdf","_mark.pdf")

fh_in = open(input_file, "rb")
pdf = PyPDF2.PdfFileReader(fh_in)

fh_wm = open(watermark_file, "rb")
watermark = PyPDF2.PdfFileReader(fh_wm)
first_page_watermark = watermark.getPage(0)





for i in range(pdf.getNumPages()):
page=pdf.getPage(i)
page.mergePage(first_page_watermark)
pdf_writer.addPage(page)



with open(outf, "wb") as filehandle_output:
# write the watermarked file to the new file
pdf_writer.write(filehandle_output)
print("finished")



if __name__ == '__main__':
input_file = "example.pdf"
output_file = "example-drafted.pdf"
watermark_file = "draft.pdfi.watermap"
#addwatermark(input_file ,watermark_file,output_file)

pdffiles = glob("*.pdf")
watermark_file = "draft.pdf.watermap"
for input_file in pdffiles:
addwatermark(input_file ,watermark_file)