批量将当前目录里的所有pdf 转化为png 格式

下面是一个 Python 脚本,可以批量将当前目录中的所有 PDF 文件转换为 PNG 格式,每页 PDF 文件会生成对应的 PNG 图片:

python 复制代码
import os
from pdf2image import convert_from_path

# 指定当前目录
directory = os.getcwd()

# 获取当前目录中所有的 PDF 文件
pdf_files = [f for f in os.listdir(directory) if f.endswith('.pdf')]

# 创建输出文件夹
output_folder = os.path.join(directory, 'output_png')
os.makedirs(output_folder, exist_ok=True)

# 批量转换 PDF 文件为 PNG
for pdf_file in pdf_files:
    pdf_path = os.path.join(directory, pdf_file)
    # 将 PDF 转换为一组图像,每页一个
    images = convert_from_path(pdf_path, dpi=300)
    
    # 保存每页的 PNG 图像
    for i, image in enumerate(images):
        image_name = f"{os.path.splitext(pdf_file)[0]}_page_{i + 1}.png"
        image_path = os.path.join(output_folder, image_name)
        image.save(image_path, 'PNG')
        print(f"Saved: {image_path}")

print("PDF to PNG conversion completed!")

说明

  • 依赖库 :该脚本需要 pdf2image 库,您可以通过以下命令安装:

    bash 复制代码
    pip install pdf2image
  • 输出文件夹 :脚本将在当前目录中创建一个 output_png 文件夹,并将转换后的 PNG 文件保存到该文件夹中。

  • DPIdpi=300 控制图片的分辨率,可以根据需要调整。

相关推荐
AI探索者15 小时前
LangGraph StateGraph 实战:状态机聊天机器人构建指南
python
AI探索者15 小时前
LangGraph 入门:构建带记忆功能的天气查询 Agent
python
FishCoderh17 小时前
Python自动化办公实战:批量重命名文件,告别手动操作
python
躺平大鹅17 小时前
Python函数入门详解(定义+调用+参数)
python
曲幽18 小时前
我用FastAPI接ollama大模型,差点被asyncio整崩溃(附对话窗口实战)
python·fastapi·web·async·httpx·asyncio·ollama
两万五千个小时21 小时前
落地实现 Anthropic Multi-Agent Research System
人工智能·python·架构
哈里谢顿1 天前
Python 高并发服务限流终极方案:从原理到生产落地(2026 实战指南)
python
用户8356290780512 天前
无需 Office:Python 批量转换 PPT 为图片
后端·python
markfeng82 天前
Python+Django+H5+MySQL项目搭建
python·django
GinoWi2 天前
Chapter 2 - Python中的变量和简单的数据类型
python