• 周五. 4月 19th, 2024

Python 中将 PDF 文件转换为图片

城主

12月 22, 2022 ,

在 Python 中将 PDF 文件转换为图片可以使用一些第三方库,例如 Python Imaging Library(PIL)、PyMuPDF 和 Wand。

下面是使用 Python Imaging Library(PIL)库将 PDF 文件转换为图片的一个简单示例:

from PIL import Image

# Open the PDF file
with open('input.pdf', 'rb') as file:
    # Create an image object
    image = Image.open(file)

    # Convert the image to a JPEG file
    image.save('output.jpg', 'JPEG')

上面的代码会打开名为 input.pdf 的 PDF 文件,然后将其转换为 JPEG 格式的图片文件 output.jpg

这是一个简单的例子,你可以根据自己的需求来编写更复杂的Python 中将 PDF 文件转换为图片代码。

如果你想要将 PDF 文件中的所有页面都转换为图片,可以使用 PyMuPDF 库。下面是一个简单的例子:

import fitz

# Open the PDF file
doc = fitz.open('input.pdf')

# Iterate through all the pages
for i in range(doc.page_count):
    # Get the current page
    page = doc[i]

    # Convert the page to an image
    image = page.getPNGImage(resolution=72)

    # Save the image to a file
    with open(f'page_{i}.png', 'wb') as file:
        file.write(image)

# Close the PDF file
doc.close()

上面的代码会打开名为 input.pdf 的 PDF 文件,然后将每一页都转换为 PNG 格式的图片文件。

阅读  Python 人工智能框架和开发步骤

如果你想要将 PDF 文件转换为其他格式的图片,可以使用 Wand 库。下面是一个简单的例子:

from wand.image import Image

# Open the PDF file
with Image(filename='input.pdf') as image:
    # Convert the image to a JPEG file
    image.save(filename='output.jpg')

上面的代码会打开名为 input.pdf 的 PDF 文件,然后将其转换为 JPEG 格式的图片文件 output.jpg

这些都是简单的例子,你可以根据自己的需求来编写更复杂的使用Python将PDF转换为图片的代码。