【问题标题】:Merge PDF pages to 1 file without generating single page files将 PDF 页面合并为 1 个文件而不生成单页文件
【发布时间】:2022-06-29 22:30:45
【问题描述】:

我们的目标是获取一组 jpg/tif 图像并将它们转换为 1 个可文本搜索的 PDF。我正在使用 Python 的 PyPDF2 和 pytesseract 来实现这一点;但是,如果不将每个页面保存为自己的 PDF,我无法找到组合这些页面的方法。原来这些集合中的一些可能是 1k-10k 页面,因此不幸的是,单独保存每个页面不再可行......这是我到目前为止所得到的:

# Convert each image to a searchable PDF
for fileset in filesets:
    merger = PdfFileMerger()
    page_path = fr".\output\pages"
    for file in fileset:
        # Load image, read with pytesseract
        path = os.path.join(download_location,file)
        img = cv2.imread(path,1)
        result = (pytesseract.image_to_pdf_or_hocr(img, lang="eng",config=tessdata_dir_config))
        # Save result as PDF
        f = open(os.path.join(path_out,getfilename.findall(file)[0])+".pdf","w+b")
        f.write(bytearray(result))
        f.close()

这对于单页效果很好,从这里我可以合并每个页面并将它们保存为一个文档,例如:

# pdfs is a list of all the single page pdf's
for page in pdfs: 
    merger.append(page)

merger.write(fr".\output\{FILE}.pdf")
merger.close();
del merger
    
# Get rid of single page files
for page in pdfs: 
    os.remove(page)

这会根据需要生成文本可搜索的 PDF,但那些单独的页面文件会破坏我的记忆。我尝试将result 对象附加到merger,这会产生AttributeError: 'bytearray' object has no attribute 'seek' 错误。我还尝试使用PyPDF2.PdfFileReader()result 对象作为PDF 读取,并得到了类似的结果。有什么想法吗?

【问题讨论】:

  • PS:因为我已经将这些 PDF 对象作为 byte() 保存在内存中,所以我认为可以以某种方式直接组合它们,类似于在文本文件中添加 \n 以创建一条新线,但我试图找到一种方法来做到这一点也是徒劳的

标签: python pdf merge pypdf2


【解决方案1】:

你需要使用BytesIO:

for fileset in filesets:
    merger = PdfFileMerger()
    page_path = fr".\output\pages"
    for file in fileset:
        # Load image, read with pytesseract
        path = os.path.join(download_location,file)
        img = cv2.imread(path,1)
        result = pytesseract.image_to_pdf_or_hocr(img, lang="eng",config=tessdata_dir_config)
        merger.append(BytesIO(result))

merger.write(fr".\output\{FILE}.pdf")

【讨论】:

    猜你喜欢
    • 2013-01-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-12
    • 2013-09-24
    • 1970-01-01
    • 2015-12-02
    相关资源
    最近更新 更多