Skip to content

Instantly share code, notes, and snippets.

@avipars
Created August 11, 2024 17:46
Show Gist options
  • Save avipars/fce3a5a3d4cc54e54acf356d97b3d7ae to your computer and use it in GitHub Desktop.
Save avipars/fce3a5a3d4cc54e54acf356d97b3d7ae to your computer and use it in GitHub Desktop.
Watermark a PDF file (all pages)
import os
from PyPDF2 import PdfReader, PdfWriter
def main():
mark_it_up("watermark.pdf", "/source/", "/output/")
def mark_it_up(watermark_file, pdf_folder, output_folder):
"""
watermark_file: str - the file that is the watermark
pdf_folder: str - the folder containing the PDF files to process
output_folder: str - the folder to save the watermarked PDFs
"""
os.makedirs(output_folder, exist_ok=True)
# Iterate through all PDF files in the folder
for filename in os.listdir(pdf_folder):
if filename.endswith(".pdf"):
# Full path to the input PDF
input_pdf_path = os.path.join(pdf_folder, filename)
# Read the input PDF
input_pdf = PdfReader(input_pdf_path)
# Create a PdfWriter for the output PDF
output_pdf = PdfWriter()
# Open the watermark PDF
with open(watermark_file, "rb") as watermark_file_obj:
watermark_pdf = PdfReader(watermark_file_obj)
watermark_page = watermark_pdf.pages[0]
# Merge the watermark with each page in the input PDF
for page in input_pdf.pages:
page.merge_page(watermark_page)
output_pdf.add_page(page)
# Define the output file name based on the original file
output_pdf_path = os.path.join(output_folder, f"output_{filename}")
try:
# Write the watermarked PDF to the output file
with open(output_pdf_path, "wb") as output_pdf_file:
output_pdf.write(output_pdf_file)
except Exception as e:
print(f"Error processing {filename}: {e}")
break # Stop processing this folder
print("Watermarking and merging complete.")
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment