0

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.

Stamp that I want to add

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)
Merkator
  • 11
  • 5
  • Unfortunately, I cannot upload any example files as they contain sensitive financial data from the company. The financial team made a mistake by stamping 1400 invoices with an incorrect job number. Therefore, I am trying to save my colleagues from the finance team days of manual work – Merkator May 08 '23 at 04:56
  • 1
    Why not just replace the annotation text, instead of removing it and adding another? – johnwhitington May 08 '23 at 10:35
  • 1
    Hm, never did replacement of the annotation, I will check how it works, thanks for the suggestion! – Merkator May 08 '23 at 15:59

0 Answers0