import os import sys from PyPDF2 import PdfReader, PdfWriter import requests import PyPDF2 def add_watermark(url, pdf_file_in, pdf_file_mark, pdf_file_out): """把水印添加到pdf中""" response = requests.get(url) with open(pdf_file_in, "wb") as pdf_file: pdf_file.write(response.content) 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_output = PdfWriter() # 读入水印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__': if len(sys.argv) < 3: print("Usage: add_watermark.py ") sys.exit(1) pdf_file_url = sys.argv[1] pdf_file_in = sys.argv[2] # 要加水印的文件名 pdf_file_out = sys.argv[3] # 加好水印的结果文件 pdf_file_mark = sys.argv[4] add_watermark(pdf_file_url, pdf_file_in, pdf_file_mark, pdf_file_out) print(pdf_file_out)