i use code below to insert text into a PDF,The inserted content 1111 is in the correct position when opening the PDF, but when querying with the read_pdfw_ith_fitz function, it is found at the end of the PDF page.Please help me see how to make the necessary modifications to succeed
import fitz # PyMuPDF
def replace_text_in_pdf(input_file, output_file, target_text, modified_text):
pdf_document = fitz.open(input_file) # 请将此路径替换为您的 PDF 文件路径
for page in pdf_document:
text_instances = page.search_for(target_text) # 查找目标文本的所有实例
for inst in text_instances:
page.add_redact_annot(inst)
page.apply_redactions()
x0, y0, x1, y1 = inst # 获取原文本的位置
page.insert_text((x0, y0), modified_text + " " + target_text, fontsize=10, color=(0, 0, 0), fontname="helv") # 插入新文本
pdf_document.save(output_file) # 请将此路径替换为您想保存的 PDF 文件路径
pdf_document.close() # 关闭 PDF 文件
def read_pdf_with_fitz(file_path, modified_text):
pdf_document = fitz.open(file_path)
for page_number in range(len(pdf_document)):
page = pdf_document[page_number]
text = page.get_text()
if modified_text in text:
print(f"Page {page_number} text found successfully.")
print(f"Page {page_number + 1}:\n{text}\n{'-' * 40}")
input_pdf = “input1.pdf”
output_pdf = “output22.pdf”
target_text = ‘因此,通过数据计算项⽬的收益相当可观。’
modified_text = ‘1111’
replace_text_in_pdf(input_pdf, output_pdf, target_text, modified_text)
read_pdf_with_fitz(output_pdf, modified_text)