#๐Ÿ”’ Replacing text in PDF

7 messages ยท Page 1 of 1 (latest)

vital urchinBOT
#

@eternal loom

Python help channel opened

Remember to:

  • Ask your Python question, not if you can ask or if there's an expert who can help.
  • Show a code sample as text (rather than a screenshot) and the error message, if you've got one.
  • Explain what you expect to happen and what actually happens.

:warning: Do not pip install anything that isn't related to your question, especially if asked to over DMs.

eternal loom
#

I don't precisely know how it works but, if it can keep the same font and styling it would be perfect, but I don't have the best idea on how PDF manipulation works

#
import fitz  # PyMuPDF

def replace_text_in_pdf(pdf_path, old_text, new_text):
    # Open the original PDF in read mode
    doc = fitz.open(pdf_path)
    for page in doc:
        text_instances = page.search_for(old_text)
        for inst in text_instances:
            # Get the rectangle coordinates of the text instance
            x0, y0, x1, y1 = inst
            # Insert the new text at the same position
            page.insert_text((x0, y0), new_text)
    # Save the modified PDF with a new filename
    modified_pdf_path = pdf_path.replace('.pdf', '_modified.pdf')
    doc.save(modified_pdf_path)
    doc.close()
    return modified_pdf_path

pdf_path = 'certificate.pdf'
old_text = '[NAME]'
new_text = 'John Doe'
modified_pdf_path = replace_text_in_pdf(pdf_path, old_text, new_text)
print("Modified PDF saved to:", modified_pdf_path)

I have this but, I've not managed to get it perfect yet. It works but, doesn't replace it adds

#

I've only found a way to insert

vital urchinBOT
#

@eternal loom

Python help channel closed

This help channel has been closed and it's no longer possible to send messages here. If your question wasn't answered, feel free to create a new post in #1035199133436354600. To maximize your chances of getting a response, check out this guide on asking good questions.

#

๐Ÿ”’ Replacing text in PDF