【问题标题】:Is it possible to extract a pdf with its white spaces in Python?是否可以在 Python 中提取带有空格的 pdf?
【发布时间】:2013-06-16 04:38:39
【问题描述】:

在创建了使用 java 和 pdfbox 提取 PDF 的工具后,我一直在尝试使用 Python 提取 pdf。

虽然 Java 实现对于同一个 pdf 是成功的,但我一直在努力在 python 中做同样的事情,因为 pdfminer 和 pypdf,并且 pypdf2 无法使用空格逐行提取 pdf。特别是 pdfminer pdf2txt 出于某种奇怪的原因将 pdf 分成 3 列然后逐行读取。

我得到的最接近的是使用a stack overflow question 的实现,不幸的是它没有保留空格。鉴于我的变量都有数字,我无法以文本形式恢复它们。

鉴于此,是否可以在 Python 中逐行提取带有空格的 pdf?

【问题讨论】:

  • 我从 pdf 获取文本最成功的方法是使用 pdftotext。如果你运行 linux,你可能已经在你的系统上安装了它。我曾经从我的 python 脚本运行pdftotext,打开文本文件,然后解析文本数据。它并不完美,但我发现 pdf 的格式和文本文件的格式之间存在关联,并用它来解析它。
  • 哦,在运行pdftotext时使用-layout

标签: python pypdf pdftotext


【解决方案1】:

以下作品在我的案例中:

from pdf2image import convert_from_path
import pytesseract

images = convert_from_path("sample.pdf")
for i,image in enumerate(images,start=1):
    image.save(f"./images/page_{i}.jpg","JPEG")

print(pytesseract.image_to_string("./images/page_1.jpg"))

这里的想法是首先将 PDF 转换为图像,然后从中读取文本。这种方法保留了空白。

依赖关系:

  • conda install -c conda-forge tesseract
  • conda 安装 pdf2image
  • conda 安装 pytesseract

【讨论】:

    【解决方案2】:

    您可以使用Aspose.PDF Cloud SDK for Python 从 PDF 中逐行提取文本以及空格。目前,它支持来自云存储(Amazon S3、DropBox、Google Drive Storage、Google Cloud Storage、Windows Azure Storage、FTP Storage 和 Aspose 默认云存储)的文件处理。

    这里是示例代码:

    import os
    import asposepdfcloud
    from asposepdfcloud.apis.pdf_api import PdfApi
    
    # Get Client Id and Client Secret from https://cloud.aspose.com
    pdf_api_client = asposepdfcloud.api_client.ApiClient(
        app_key='xxxxxxxxxxxxxxxxxx',
        app_sid='xxxx-xxxx-xxxx-xxxx-xxxxxxxxxx')
    
    pdf_api = PdfApi(pdf_api_client)
    temp_folder="Temp"
    
    #upload PDF file to storage
    data_file = "C:/Temp/02_pages.pdf"
    remote_name="02_pages.pdf"
    pdf_api.upload_file(temp_folder + '/' + remote_name,data_file)
    
    llx = 0
    lly = 0
    urx = 0
    ury = 0
    
    response = pdf_api.get_text(remote_name, llx, lly, urx, ury, folder= temp_folder)
    
    for i in response.text_occurrences.list:
        print(i.text)
    
    

    P.S:我是 Aspose 的开发布道者

    【讨论】:

      猜你喜欢
      • 2020-11-12
      • 1970-01-01
      • 2020-07-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多