from PyPDF2 import PdfReader, PdfWriterdef add_watermark(pdf_file_in, pdf_file_mark, pdf_file_out):"""把水印添加到pdf中"""pdf_output = PdfWriter()input_stream = open(pdf_file_in, 'rb')pdf_input = PdfReader(input_stream, strict=False)# 获取PDF文件的页数# pageNum = pdf_input.getNumPages()pageNum = len(pdf_input.pages)# 读入水印pdf文件pdf_watermark = PdfReader(open(pdf_file_mark, 'rb'), strict=False)# 给每一页打水印for i in range(pageNum):# page = pdf_input.getPage(i)page = pdf_input.pages[i]page.merge_page(pdf_watermark.pages[0])page.compress_content_streams() # 压缩内容pdf_output.add_page(page)pdf_output.write(open(pdf_file_out, 'wb'))if __name__ == '__main__':pdf_file_in = 'example.pdf' #要加水印的原始pdf文件pdf_file_out = 'watermarked.pdf' #加好水印的结果文件pdf_file_mark = 'watermark.pdf' #要加的水印文件add_watermark(pdf_file_in, pdf_file_mark, pdf_file_out)
word中可以自己编辑水印文件:
点击设计-水印即可编辑水印文件,效果如下:
example.pdf:
最终效果: