you can use the Python library PyPDF2, which is a pure-python PDF toolkit that allows you to manipulate and modify PDF documents. Here is an example of how you can use PyPDF2 to add a watermark with a page number to each page of a PDF document:
import os
import PyPDF2
# Get the path to the folder containing the PDF documents
pdf_folder_path = '/path/to/pdf/folder'
# Create a list of PDF files in the folder, sorted by filename
pdf_files = sorted([f for f in os.listdir(pdf_folder_path) if f.endswith('.pdf')])
# Loop through each PDF file in the list
for i, pdf_file in enumerate(pdf_files):
# Open the PDF file for reading and writing
with open(os.path.join(pdf_folder_path, pdf_file), 'rb+') as pdf:
# Create a PdfFileReader object for the PDF file
pdf_reader = PyPDF2.PdfFileReader(pdf)
# Create a PdfFileWriter object for the output PDF file
pdf_writer = PyPDF2.PdfFileWriter()
# Loop through each page in the PDF file
for page_num in range(pdf_reader.getNumPages()):
# Get the current page from the PDF file
page = pdf_reader.getPage(page_num)
# Create a watermark object with the page number and position it at the bottom-right corner of the page
watermark = PyPDF2.pdf.PageObject.createBlankPage(None, page.mediaBox.getWidth(), page.mediaBox.getHeight())
watermark.mergeScaledTranslatedPage(page, 1, 0, 0, 1, 0, 0)
watermark.mergeScaledTranslatedPage(PyPDF2.pdf.PageObject.createTextObject(PyPDF2.pdf.PdfContentByte(None), str(i+1)), 1, 0, 0, 1, page.mediaBox.getWidth()-100, 20)
# Merge the watermark with the current page and add it to the output PDF file
page.mergePage(watermark)
pdf_writer.addPage(page)
# Save the output PDF file with the watermark
pdf_writer.write(pdf)