使用 PyMuPDF 的编辑功能可能就足够了。该方法:
必须注意掌握原始字体,以及新文本是否比原始文本长/短。
import fitz # import PyMuPDF
doc = fitz.open("myfile.pdf")
page = doc[number] # page number 0-based
# suppose you want to replace all occurrences of some text
disliked = "delete this"
better = "better text"
hits = page.search_for("delete this") # list of rectangles where to replace
for rect in hit:
page.add_redact_annot(rect, better, fontname="helv", fontsize=11,
align=fitz.TEXT_ALIGN_CENTER, ...) # more parameters
page.apply_annots(images=fitz.PDF_REDACT_IMAGE_NONE) # don't touch images
doc.save("replaced.pdf", garbage=3, deflate=True)
Run Code Online (Sandbox Code Playgroud)
这非常适合短文本和中等质量期望。
通过更多的努力,可以识别原始字体属性、颜色、字体大小等,以产生接近完美的结果。