【发布时间】:2021-10-18 09:24:09
【问题描述】:
我在网上找到了一些关于如何在扫描 PDF 时使其可搜索的指南。但是,我目前正在努力弄清楚如何为多页 PDF 执行此操作。
我的代码采用多页 PDF,将每个页面转换为 JPG,在每个页面上运行 OCR,然后将其转换为 PDF。但是,只返回最后一页。
import pytesseract
from pdf2image import convert_from_path
pytesseract.pytesseract.tesseract_cmd = 'directory'
TESSDATA_PREFIX = 'directory'
tessdata_dir_config = '--tessdata-dir directory'
# Path of the pdf
PDF_file = r"pdf directory"
def pdf_text():
# Store all the pages of the PDF in a variable
pages = convert_from_path(PDF_file, 500)
image_counter = 1
for page in pages:
# Declare file names
filename = "page_"+str(image_counter)+".jpg"
# Save the image of the page in system
page.save(filename, 'JPEG')
# Increment the counter to update filename
image_counter = image_counter + 1
# Variable to get count of total number of pages
filelimit = image_counter-1
outfile = "out_text.pdf"
# Open the file in append mode so that all contents of all images are added to the same file
f = open(outfile, "a")
# Iterate from 1 to total number of pages
for i in range(1, filelimit + 1):
filename = "page_"+str(i)+".jpg"
# Recognize the text as string in image using pytesseract
result = pytesseract.image_to_pdf_or_hocr(filename, lang="eng", config=tessdata_dir_config)
f = open(outfile, "w+b")
f.write(bytearray(result))
f.close()
pdf_text()
如何为所有页面运行此程序并输出一个合并的 PDF?
【问题讨论】:
-
你为什么使用
f = open(outfile, "w+b")?您已经在for-loop 之前打开它以附加f = open(outfile, "a")并且您不应该一次又一次地打开它。你应该在for-loop 之后关闭它,而不是在里面