【问题标题】:How to create a multiple page pdf with pytesseract?如何使用 pytesseract 创建多页 pdf?
【发布时间】:2021-05-23 14:45:03
【问题描述】:

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

代码如下:

images = convert_from_path(name,poppler_path=r'C:\Program Files\poppler-0.68.0\bin')

    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)

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

提前致谢!

【问题讨论】:

    标签: python python-3.x python-tesseract


    【解决方案1】:

    尝试使用 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()
    

    【讨论】:

      猜你喜欢
      • 2017-06-28
      • 2012-07-03
      • 2012-01-23
      • 1970-01-01
      • 2021-11-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多