pdf_watermark.py 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. import PyPDF2
  2. import plac
  3. from pathlib import Path
  4. def add_watermark(input_file):
  5. watermark_file = 'c:/tools/template/Briefbogen_GC_Jahnstr_GmbH.pdf'
  6. output_file = Path(input_file).parent.joinpath("mit_Briefpapier", Path(input_file).name)
  7. if not output_file.parent.exists():
  8. output_file.parent.mkdir()
  9. with open(input_file, "rb") as filehandle_input:
  10. # read content of the original file
  11. pdf = PyPDF2.PdfFileReader(filehandle_input)
  12. with open(watermark_file, "rb") as filehandle_watermark:
  13. # read content of the watermark
  14. watermark = PyPDF2.PdfFileReader(filehandle_watermark)
  15. # get first page of the watermark PDF
  16. first_page_watermark = watermark.getPage(0)
  17. # create a pdf writer object for the output file
  18. pdf_writer = PyPDF2.PdfFileWriter()
  19. # get first page of the original PDF
  20. for i in range(pdf.getNumPages()):
  21. current_page = pdf.getPage(i)
  22. # merge the two pages
  23. current_page.mergePage(first_page_watermark)
  24. # add page
  25. pdf_writer.addPage(current_page)
  26. with open(output_file, "wb") as filehandle_output:
  27. # write the watermarked file to the new file
  28. pdf_writer.write(filehandle_output)
  29. def add_watermark_to_folder(base_dir):
  30. for filename in Path(base_dir).glob('*.pdf'):
  31. add_watermark(str(filename))
  32. print(filename.name)
  33. if __name__ == '__main__':
  34. plac.call(add_watermark_to_folder)
  35. # add_watermark_to_folder(os.path.dirname(__file__) + '/data/')