如何使用pytesseract创建多页pdf



我试图在pdf中只标记几个单词,根据结果,我想只使用pytesseract制作一个新的pdf。

这是代码:

images = convert_from_path(name,poppler_path=r'C:Program Filespoppler-0.68.0bin')
for i in images:
img = cv.cvtColor(np.array(i),cv.COLOR_RGB2BGR)
d = pytesseract.image_to_data(img,output_type=Output.DICT,lang='eng+equ',config="--psm 6")
boxes = len(d['level'])
for i in range(boxes):
for e in functionEvent: #functionEvent is a list of strings
if e in d['text'][i]:
(x,y,w,h) = (d['left'][i],d['top'][i],d['width'][i],d['height'][i])
cv.rectangle(img,(x,y),(x+w,y+h),(0,255,0),2)

pdf = pytesseract.image_to_pdf_or_hocr(img,extension='pdf')
with open('results.pdf','w+b') as f:
f.write(pdf)

我试过什么:

with open('results.pdf','a+b') as f:
f.write(pdf)

如果你知道我该怎么解决这个问题,请告诉我。此外,我根本不在乎你是否推荐另一个模块或你的意见,我应该如何编写代码。

提前感谢!

尝试使用PyPDF2将PDF链接在一起。首先,你用tesseract OCR从pdf中提取文本,并将其存储到列表对象中,如下所示:

for filename in tqdm(os.listdir(in_dir)):
img = Image.open(os.path.join(in_dir,filename))
pdf = pytesseract.image_to_pdf_or_hocr(img, lang='slk', extension='pdf')
pdf_pages.append(pdf)

然后遍历每个处理过的图像或文件,读取字节并使用PdfFileReader添加页面,如下所示(不要忘记导入io(:

pdf_writer = PdfFileWriter()
for page in pdf_pages:
pdf = PdfFileReader(io.BytesIO(page))
pdf_writer.addPage(pdf.getPage(0))

最后创建文件并将数据存储到其中:

file = open(out_dir, "w+b")
pdf_writer.write(file)
file.close()

最新更新