PDF转图片

使用 PyMuPDF 和 PIL 将 PDF 转换为图片并合并

1. 简介

本教程将指导您如何使用 Python 和 PyMuPDF 库将 PDF 文档的每一页转换为图片,并使用 PIL(Pillow)库将这些图片垂直合并成一张长图片。这种方法对于创建长卷轴式的图像或文档非常有用。

2. 环境设置

在开始之前,请确保您的环境中已安装了 Python 和以下库:

  • PyMuPDF:用于处理 PDF 文件。
  • Pillow(PIL):用于图像处理。 您可以使用 pip 安装这些库(如果尚未安装):
bash 复制代码
pip install PyMuPDF Pillow

3. 脚本

python 复制代码
import fitz  # PyMuPDF


def convert_pdf_to_images(pdf_path, output_folder, resolution, color_mode='rgb'):
    # 打开 PDF 文件
    pdf_document = fitz.open(pdf_path)

    # 遍历 PDF 中的每一页
    for page_number in range(len(pdf_document)):
        page = pdf_document[page_number]

        # 获取页面的原始大小(以点为单位)
        zoom_x = resolution / page.rect.width
        zoom_y = resolution / page.rect.height

        # 使用最小的缩放比例以确保整个页面都适应目标分辨率
        zoom = min(zoom_x, zoom_y)

        # 创建一个矩阵来应用缩放和抗锯齿
        mat = fitz.Matrix(zoom, zoom)

        # 将 PDF 页面转换为图片,指定分辨率、颜色模式和抗锯齿
        pix = page.get_pixmap(matrix=mat, alpha=False, colorspace=color_mode)

        # 定义输出图片的路径
        output_path = f"{output_folder}/page_{page_number + 1}.png"

        # 保存图片
        pix.save(output_path)

    # 关闭 PDF 文件
    pdf_document.close()


# 使用函数
if __name__ == '__main__':
    convert_pdf_to_images("E:/workCode/pythonScript/resources/test.pdf", './resources/output', resolution=2048,
                          color_mode='rgb')
python 复制代码
import fitz  # PyMuPDF
from PIL import Image


def convert_pdf_to_images(pdf_path, resolution):
    # 打开 PDF 文件
    pdf_document = fitz.open(pdf_path)

    # 存储所有转换后的图片
    images = []

    # 遍历 PDF 中的每一页
    for page_number in range(len(pdf_document)):
        page = pdf_document[page_number]
        # 获取页面的原始大小(以点为单位)
        zoom_x = resolution / page.rect.width
        zoom_y = resolution / page.rect.height
        # 使用最小的缩放比例以确保整个页面都适应目标分辨率
        zoom = min(zoom_x, zoom_y)

        # 创建一个矩阵来应用缩放和抗锯齿
        mat = fitz.Matrix(zoom, zoom)
        # 将 PDF 页面转换为图片
        pix = page.get_pixmap(matrix=mat)

        # 使用 PIL 的 Image 对象打开图片
        image = image = Image.frombytes("RGB", (pix.width, pix.height), pix.samples)

        # 将图片添加到列表中
        images.append(image)

    # 合并所有图片
    total_height = sum(image.size[1] for image in images)
    combined_image = Image.new('RGB', (images[0].size[0], total_height))

    current_height = 0
    for image in images:
        combined_image.paste(image, (0, current_height))
        current_height += image.size[1]

    # 关闭 PDF 文件
    pdf_document.close()

    return combined_image


# 使用函数
combined_image = convert_pdf_to_images("E:/workCode/pythonScript/resources/test.pdf", resolution=2048)

# 保存合并后的图片
combined_image.save("test.png")

我们将使用两个脚本。第一个脚本 convert_pdf_to_images.py 将 PDF 文件的每一页转换为图片。第二个脚本 merge_images.py 将这些图片合并成一张长图片。

脚本 1:将 PDF 文件的每一页转换为图片

此脚本执行以下操作:

  • 打开指定的 PDF 文件。
  • 遍历 PDF 的每一页。
  • 计算合适的缩放比例,以确保每一页适应目标分辨率。
  • 使用 PyMuPDF 的 get_pixmap() 方法将每一页转换为图片。
  • 将转换后的图片保存到指定的文件夹。 重要函数和参数:
  • fitz.open(): 打开 PDF 文件。
  • get_pixmap(): 获取页面的像素图。
  • save(): 保存图片到文件系统。
脚本 2:将 PDF 文件的每一页转换为图片并合并成一张图片

此脚本执行以下操作:

  • 打开 PDF 文件并遍历每一页。
  • 将每一页转换为图片,并保存到一个列表中。
  • 计算合并后图片的总高度。
  • 使用 PIL 的 Image.new() 创建一个新的空白图片。
  • 将所有图片垂直拼接起来。
  • 保存合并后的图片。 重要函数和参数:
  • Image.frombytes(): 从二进制数据创建 PIL 的 Image 对象。
  • Image.new(): 创建一个新的图片。
  • paste(): 将图片粘贴到另一个图片上。
相关推荐
一只小小程序猿18 分钟前
Python计算机视觉编程 第九章 图像分割
开发语言·python·计算机视觉
AI原吾23 分钟前
探索Mem0:AI的智能记忆层
人工智能·python·ai·mem0
C7211BA2 小时前
多智能体强化学习示例
python
luthane5 小时前
python 实现bailey borwein plouffe算法
开发语言·python·算法
大侠之运维5 小时前
在excel中使用python?
开发语言·python·excel
Fightting885 小时前
Openpyxl 插入数据添加数据
前端·windows·python
Mr_Happy_Li6 小时前
网络模型的保存与读取
人工智能·python·深度学习·神经网络·计算机视觉·网络模型
子午6 小时前
鸟类识别系统Python+卷积神经网络算法+深度学习+人工智能+TensorFlow+ResNet50算法模型+图像识别
人工智能·python·深度学习
宇梵文书C6 小时前
解决tiktoken库调用get_encoding时SSL超时
python·nlp
chusheng18407 小时前
Python 中的 Socket 编程入门
开发语言·网络·python