代码之家  ›  专栏  ›  技术社区  ›  Bleached

使用pdf2image将PDF转换为PNG

  •  0
  • Bleached  · 技术社区  · 3 年前

    我正在尝试使用pdf2image将PDF转换为PNG文件类型,而不使用路径。我想将InMemoryUploadedFile传递到函数中进行转换,而不是指定PDF文件的路径。我不认为pdf2image可以做到这一点,但我想知道是否有其他方法可以做到这?

    下面的代码在我的主要项目之外进行测试。在将函数集成到我的项目中之前,试着弄清楚如何做到这一点。file=从路径打开,但随后作为InMemoryUploadedFile传入

    from pdf2image import convert_from_path, convert_from_bytes
    
    
    file = open(r"PDF\pdf_files\NDB.pdf")
    images = convert_from_path(file, poppler_path=r"C:\Python\poppler\poppler-23.07.0\Library\bin")
    
    for pdf in images:
        for i in range(len(pdf)):
            # Save pages as images in the pdf
            images[i].save(f'PDF\image_mods\image_converted_{i+1}.png', 'PNG')
    
    1 回复  |  直到 3 年前
        1
  •  0
  •   Dulan Jayawickrama    3 年前

    pdf2image不直接支持转换InMemoryUploadedFile对象,这是正确的。但是,您可以使用PyPDF2库从InMemoryUploadedFile读取PDF内容,然后使用pdf2image将其转换为图像。以下是如何实现这一目标的示例

    from io import BytesIO
    import PyPDF2
    from pdf2image import convert_from_bytes
    
    # Assuming "file" is an InMemoryUploadedFile object containing the PDF content
    # Read the PDF content from the InMemoryUploadedFile
    pdf_content = file.read()
    
    # Create a BytesIO object to handle the PDF content
    pdf_stream = BytesIO(pdf_content)
    
    # Use PyPDF2 to get the number of pages in the PDF (optional step)
    pdf_reader = PyPDF2.PdfFileReader(pdf_stream)
    num_pages = pdf_reader.numPages
    
    # Convert the PDF content to images using pdf2image
    images = convert_from_bytes(pdf_content, poppler_path=r"C:\Python\poppler\poppler-23.07.0\Library\bin")
    
    # Save each image
    for i, pdf in enumerate(images):
        # Save pages as images in the pdf
        pdf.save(f'PDF\image_mods\image_converted_{i + 1}.png', 'PNG')
    

    在这里,我们使用BytesIO从InMemoryUploadedFile创建一个PDF内容流。然后,我们使用PyPDF2读取PDF内容并获取PDF中的页数(如果您不需要页数,则此步骤是可选的)。最后,我们将PDF内容(以字节为单位)传递给pdf2image convert_from_bytes 函数将其转换为图像,然后将图像保存为PNG文件。

    如果您还没有安装PyPDF2和pdf2image库,请确保同时安装它们

    pip install PyPDF2
    pip install pdf2image