I am working on a script that loops through a directory of PDF files, checks if they contain a stamp with the subject 'Brick - Entered by Justin', removes that stamp, and replaces it with a stamp from a variable called 'stamp_path'.
The 'stamp_path' variable contains a blank PDF file with the stamp from the attached snippet. The old stamp looks same, just it has different credentials and job number.
Although my code successfully removes the old stamp and adds the new one, the new stamp is not being placed at the correct position (i.e., the same coordinates as the old stamp).
Any ideas would be greatly appreciated!
Here is my code so far:
from pdfrw import PdfReader, PdfWriter, PageMerge, IndirectPdfDict
import os
# define the paths to the stamps and the PDF directory
stamp_path = r"C:\Users\Stamping\SampleStamp\STAMP BRICK_1.pdf"
pdf_directory = r"C:\Users\Stamping\PDF"
for filename in os.listdir(pdf_directory):
input_file = os.path.join(pdf_directory, filename)
if filename.endswith(".pdf"):
old_stamp_pos=[]
finished = "signed" + filename
pdf_path = os.path.join(pdf_directory, filename)
output_file = os.path.join(pdf_directory, finished)
reader_input = PdfReader(input_file)
for i in range(len(reader_input.pages)):
# get the page
page = reader_input.pages[i]
# get the annotations on the page
annotations = page.Annots or []
for annotation in annotations:
if annotation['/Subj'] == '(Brick - Entered by Justin)':
# get the position of the old stamp
old_stamp_pos = annotation['/Rect']
# remove the old stamp
page.Annots.remove(annotation)
writer_output = PdfWriter()
watermark_input = PdfReader(stamp_path)
watermark = watermark_input.pages[0]
merger = PageMerge(reader_input.pages[i])
#define x and y for the new stamp
watermark.x = old_stamp_pos[0]
watermark.y = old_stamp_pos[1]
merger.render()
# write the modified content to disk
writer_output.write(output_file, reader_input)