python pdf文件转图片

在Python中,有很多的第三方库可以用于PDF文件的转换,比如PyPDF2和pdf2image。

其中PyPDF2可以从PDF文件中提取每一页并将其保存为图像文件,需要安装Pillow库。

pdf2image则直接将PDF文件转换为PNG或JPEG图像文件,可以使用ImageMagick或Ghostscript作为后台渲染引擎。

以下是使用这两个库的示例代码:

  1. 使用PyPDF2库将PDF文件中的第一页转换为图像文件
python 复制代码
import io
import os
from PIL import Image
import PyPDF2

pdf_file = "example.pdf"
page_number = 0
output_file = "output.jpg"

# 打开PDF文件并读取第一页
with open(pdf_file, "rb") as f:
    pdf = PyPDF2.PdfFileReader(f)
    page = pdf.getPage(page_number)

    # 获取页面大小和旋转角度
    bbox = page.mediaBox
    rotate = page.get('/Rotate', 0)

    # 转换为Pillow图像对象
    img = page.toImage()
    img = img.convert("RGB")
    img = img.rotate(-rotate)

    # 保存为JPEG图像文件
    img.save(output_file, "JPEG")
    
    print(f"{pdf_file}的第{page_number+1}页已保存为{output_file}")
  1. 使用pdf2image库将PDF文件转换为PNG图像文件
python 复制代码
import os
from pdf2image import convert_from_path

pdf_file = "example.pdf"
output_file = "output.png"

# 将PDF文件转换为PNG图像列表
images = convert_from_path(pdf_file)

# 获取第一页并保存为图像文件
image = images[0]
image.save(output_file, "PNG")

print(f"{pdf_file}的第一页已保存为{output_file}")
相关推荐
gugucoding3 分钟前
21. 【C语言】打包不同类型:结构体
c语言·开发语言
2601_954706499 分钟前
云手机 API 自动化实战:Python 批量控机、挂机脚本完整实现
python·智能手机·自动化
Brookty11 分钟前
【JavaEE】线程安全(一).4:写块串行保安全、CAS
java·开发语言·java-ee·多线程·线程安全
F20226974861 小时前
西门子 PLC 与 C# 通信
开发语言·c#
gugucoding1 小时前
31. 【C语言】堆栈与队列的实现
c语言·开发语言·数据结构·链表
万联WANFLOW2 小时前
多分支企业组网,IP 网段到底该怎么规划
开发语言·php
阿里嘎多学长2 小时前
2026-07-07 GitHub 热点项目精选
开发语言·程序员·github·代码托管
Alan_6914 小时前
聊聊 Swagger/Postman/Apifox 的真实选型与 Python 项目实战
python·测试工具·postman
cookies_s_s4 小时前
C++ 字符串动态创建对象 -- 工厂模式、自动注册、模板递归动态调用
服务器·开发语言·c++
智慧物业老杨5 小时前
物业绿化数智化权责管控方案:基于工单平台的双层权限追溯模块落地实践
python