如何解决使用Fitz在带注释的文本周围裁切pdf区域
问题陈述
- 阅读pdf并搜索单词。
- 如果找到了单词,请对该单词进行注释,并从pdf文件中的注释文本周围裁剪一个区域。
- 每个裁剪的图像应仅具有一个注释。
库和版本
- python-3.6
- fitz-0.0.1.dev2
- pymupdf-1.17.5
问题面对
对于前两个迭代,注释是完美的,并且裁剪也可以按预期完美地工作。但是,通过迭代文本实例中搜索词的下一次出现,然后在该区域周围进行裁剪,并且搜索词的注释也会失败。 找不到解决此问题的方法。
def cropPdf( pdfName,word):
c=0
# opening the pdf file using fitz
fitz_doc=fitz.open(pdfName)
# getting first page of the doc
fitz_page=fitz_doc[0]
# finding all instances where the searchword is found
text_instances=fitz_page.searchFor(word)
# Iterating through each text instances
for text_cord in text_instances:
c=c+1
pdfPath = "./" + pdfName + ".pdf"
# To add highlight(Rectangle Annotation) around the search word
highlight = fitz_page.addRectAnnot(text_cord)
# getting the bounding box cordinate
x0,y0,x1,y1=highlight.rect
# here i set the cropping area around the annotated text
fitz_page.setCropBox(fitz.Rect(x0+600,y0+600,x0-600,y0-600))
#
pix=fitz_page.getPixmap()
print(fitz_page.number)
base_name_highlight="output"+str(c)+".png"
# saving the cropped area as png file
pix.writeImage("./highlight_folder/"+base_name_highlight)
# Deleting the marked annotation which helps me to avoid duplicate annotation inside a cropped area,# when starting to annotate the next occurence of the word to annotate while iterating.
fitz_page.deleteAnnot(highlight)
cropPdf(pdfName="A4_4.pdf",word="INSULATION")
结果图像
解决方法
对裁剪框的更改可能会影响页面的所有坐标。因此,在进入注释循环之前,我应该在变量中指定cropbox的初始状态。在每次迭代结束时,我都应重置为初始的裁剪框,这将有助于在不更改坐标的情况下注释下一次发生的情况
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。