如何在不使用pdf2Image的情况下将多页PDF文件转换为图像?

问题描述 投票:0回答:1

我正在尝试使用 pdf2image 将多页 PDF 转换为图像变量,就像在 Textractor 代码中完成的那样,以便我可以在 LazyDocument 中使用它:

import pdf2image
from pdf2image import convert_from_path, convert_from_bytes
import boto3
from textractcaller import call_textract, OutputConfig
from textractcaller.t_call import Textract_Call_Mode, Textract_API, get_full_json


file_source = 's3://mybucket/my/path/to/file.pdf'
bucket = 'mybucket'
key = 'my/path/to/file.pdf'

session = boto3.session.Session(region_name= 'us-east-1')
textract_client = session.client("textract", region_name= 'us-east-1')

output_config = OutputConfig(s3_bucket=bucket, s3_prefix=key)
response = call_textract(
            input_document=file_source,
            ouptput_config = output_config,
            features=[TextractFeatures.FORMS, TextractFeatures.TABLES, TextractFeatures.SIGNATURES, TextractFeatures.LAYOUT],
            return_job_id=True,
            force_async_api=True,
            call_mode=Textract_Call_Mode.FORCE_ASYNC,
            boto3_textract_client= textract_client,
            job_done_polling_interval=1,
        )

s3_client = session.client("s3")

file_obj = s3_client.get_object(Bucket=bucket, Key=key).get("Body").read()
images = convert_from_bytes(bytearray(file_obj))

LazyDoc = LazyDocument(
        response["JobId"],
        Textract_API.ANALYZE,
        textract_client= textract_client,
        images=images,
        output_config=output_config,
    )

虽然使用 pip install 时可以正确安装软件包

pdf2image
。我收到错误:

PDFInfoNotInstalledError: Unable to get page count. Is poppler installed and in PATH?

我见过一些解决方案,要求下载必要的文件并指定 poppler_path。但是,由于权限问题,我不允许将任何文件从网上上传到所需的空间。有没有另一种方法可以在不使用 pdf2image 的情况下获取

images
变量?

python image pdf pdf2image
1个回答
0
投票

这是 PyMuPDF 的解决方案:

import fitz  # PyMuPDF

doc = fitz.open("input.pdf")
for page in doc:
    pix = page.get_pixmap(dpi=150)  # pymupdf's internal image format, at DPI=150
    pix.save("page-%i.png" % page.number)  # save page as PNG

要不输出到文件但返回 PNG 格式的

bytes
对象,请酌情使用
pix.tobytes("png")
。其他图像格式 (JPEG) 也可用。

注意:我是PyMuPDF的维护者和原始创建者。

© www.soinside.com 2019 - 2024. All rights reserved.