add_watermark.py 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. import os
  2. import sys
  3. from PyPDF2 import PdfReader, PdfWriter
  4. import requests
  5. import PyPDF2
  6. def add_watermark(url, pdf_file_in, pdf_file_mark, pdf_file_out):
  7. """把水印添加到pdf中"""
  8. response = requests.get(url)
  9. with open(pdf_file_in, "wb") as pdf_file:
  10. pdf_file.write(response.content)
  11. input_stream = open(pdf_file_in, 'rb')
  12. pdf_input = PdfReader(input_stream, strict=False)
  13. # 获取PDF文件的页数
  14. # pageNum = pdf_input.getNumPages()
  15. pageNum = len(pdf_input.pages)
  16. pdf_output = PdfWriter()
  17. # 读入水印pdf文件
  18. pdf_watermark = PdfReader(open(pdf_file_mark, 'rb'), strict=False)
  19. # 给每一页打水印
  20. for i in range(pageNum):
  21. # page = pdf_input.getPage(i)
  22. page = pdf_input.pages[i]
  23. page.merge_page(pdf_watermark.pages[0])
  24. page.compress_content_streams() # 压缩内容
  25. pdf_output.add_page(page)
  26. pdf_output.write(open(pdf_file_out, 'wb'))
  27. if __name__ == '__main__':
  28. if len(sys.argv) < 3:
  29. print("Usage: add_watermark.py <pdf_file_in> <pdf_file_out> <pdf_file_mark>")
  30. sys.exit(1)
  31. pdf_file_url = sys.argv[1]
  32. pdf_file_in = sys.argv[2] # 要加水印的文件名
  33. pdf_file_out = sys.argv[3] # 加好水印的结果文件
  34. pdf_file_mark = sys.argv[4]
  35. add_watermark(pdf_file_url, pdf_file_in, pdf_file_mark, pdf_file_out)
  36. print(pdf_file_out)