#python #pypdf2 #pdfminer
#python #pypdf #pdfminer
Вопрос:
Я хочу очистить документ PDF, и мне нужны координаты полей ввода (нижняя левая угловая точка текстового поля). Есть ли способ добиться этого с помощью какой-либо библиотеки python, такой как PyPDF2 или PDFMiner? следующие изображения могут помочь понять проблему
Ответ №1:
Обычно такие поля представляют собой либо повторение точек, либо подчеркивание. Вы можете извлечь текстовые строки файла PDF с помощью PyMuPDF и использовать выражение регулярного выражения ( 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)
`