问题描述
我想抓取一个pdf文档,并且我想输入字段的坐标(文本字段的左下角)。有没有办法使用PyPDF2或pdfminer之类的python库来实现这一点?以下图片可以帮助您了解问题所在
解决方法
通常,这些字段要么是句号的重复,要么是下划线。您可以使用 PyMuPDF 提取 pdf 文件的文本行,并使用正则表达式 (import re
) 来识别此类重复,然后在识别出匹配项时将坐标保存到列表或类似内容中。
下面的代码执行此操作,只是将 (x0,y0,x1,y1) 保存为左下角 (x0,y0) 和右上角 (x1,y1) 的坐标 - 您可以提取您想要的坐标需要。
def whichFields(self,txtline):
reg = re.compile(r"(…|\..)\1+")
self.matches.append(reg.finditer(txtline))
return self.matches
# Uses PyMuPDF to find box coordinates of the fields in matches[]
# returns a list of the coordinates in the order which they
# appear in matches[].
def whereFields(self):
global c
count = 0
for page in self.doc:
field_areas = []
c = self.newCanvas(count)
page_num = count
count += 1
mts = []
txtlines = page.getText("text").split("\n") # using doc opened in fitz,splitting all text lines in page
prev_area = []
for j in txtlines:
mts.append(self.whichFields(j))
# These for loops access the result of the regex search and then ultimately pass
# the matching strings to searchFor() which returns a list of coordinates of the
# rectangles in which the searched "fields" are found.
for data in mts:
for match in data:
for i in match:
# extracts the matching string and searches for its rect coordinates.
self.areas = page.searchFor(i[1])
for area in self.areas:
field_areas.append(area)
`