为了修改pdf的文本, 在pymupdf官方手册查了一通,没看到明显的说明,然后到github的讨论区看了发现了修改pdf的方案,在此记录一下
参考链接: https://github.com/pymupdf/PyMuPDF/discussions/1019

根据前文说明,我们发现使用修订注释可以删除文本块的,因此我们可以利用该方法进行一些文本块的删除操作,具体示例如下:

import fitz
doc = fitz.open("PDF文件路径")
page = doc.load_page(0)
# 遍历文本块,找到对应的文本块
def find_textbox(page:fitz.Page,keyword:str)->dict:
info = page.get_text('dict')
for block in info['blocks']:
for line in block['lines']:
for span in line['spans']:
text = span.get('text','').replace(' ','')
if text == keyword:
return span
target = find_textbox(page,'年月日')
page.add_redact_annot(target['bbox'])
page.apply_redactions()
doc.save("保存文件路径")

修改文本块,就是在添加修订注释后,增加文本块即可
代码如下:
import fitz
doc = fitz.open("PDF文件路径")
page = doc.load_page(0)
# 遍历文本块,找到对应的文本块
def find_textbox(page:fitz.Page,keyword:str)->dict:
info = page.get_text('dict')
for block in info['blocks']:
for line in block['lines']:
for span in line['spans']:
text = span.get('text','').replace(' ','')
if text == keyword:
return span
target = find_textbox(page,'年月日')
page.add_redact_annot(target['bbox'],'今夕复何夕',fontname='china-s',fontsize=target['size'])
page.apply_redactions()
doc.save("保存文件路径")
