批量将当前目录里的所有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 控制图片的分辨率,可以根据需要调整。

相关推荐
aqi0013 小时前
15天学会AI应用开发(八)使用向量数据库实现RAG功能
人工智能·python·大模型·ai编程·ai应用
Csvn14 小时前
`functools.lru_cache` —— 一行代码搞定缓存加速
后端·python
金銀銅鐵1 天前
[Python] 从《千字文》中随机挑选汉字
后端·python
cup111 天前
[技术复盘] Windows Python 打包实战:Nuitka 环境踩坑总结与 CI 自动化构建全指南
python·ai·环境变量·ci·nuitka·skill
aqi002 天前
15天学会AI应用开发(七)有了大模型为什么还要引入RAG
人工智能·python·大模型·ai编程·ai应用
金銀銅鐵2 天前
用 Python 实现 Take-Away 游戏
python·游戏
copyer_xyf2 天前
Agent 流程编排
后端·python·agent
copyer_xyf2 天前
Agent RAG
后端·python·agent