利用python 检测当前目录下的所有PDF 并转化为png 格式

以下是一个完整的 Python 脚本,用于检测当前目录下的所有 PDF 文件并将每一页转换为 PNG 格式:

python 复制代码
import os
from pdf2image import convert_from_path

# 设置输出图像的 DPI(分辨率)
DPI = 300

# 获取当前目录
current_directory = os.getcwd()

# 获取所有 PDF 文件
pdf_files = [file for file in os.listdir(current_directory) if file.endswith('.pdf')]

# 检查是否有 PDF 文件
if not pdf_files:
    print("当前目录没有找到任何 PDF 文件。")
else:
    # 创建保存 PNG 文件的文件夹
    output_directory = os.path.join(current_directory, "pdf_to_png_output")
    os.makedirs(output_directory, exist_ok=True)
    
    for pdf_file in pdf_files:
        pdf_path = os.path.join(current_directory, pdf_file)
        print(f"正在处理: {pdf_file}")
        
        # 转换 PDF 为图像
        try:
            images = convert_from_path(pdf_path, dpi=DPI)
            for i, image in enumerate(images):
                output_file = os.path.join(output_directory, f"{os.path.splitext(pdf_file)[0]}_page_{i+1}.png")
                image.save(output_file, "PNG")
                print(f"已保存: {output_file}")
        except Exception as e:
            print(f"处理文件 {pdf_file} 时出错: {e}")

print("转换完成。")

使用说明

  1. 安装依赖:

    请确保安装了 pdf2imagepopplerpdf2image 需要依赖 poppler-utils)。

    bash 复制代码
    conda install pdf2image

    对于 poppler,可以根据你的操作系统安装:

    • Windows:下载 Poppler 的二进制文件并将其添加到系统 PATH。
    • macOS :通过 brew install poppler 安装。
    • Linux :通过 apt install poppler-utils 安装。
  2. 运行脚本:

    将脚本保存为 convert_pdf_to_png.py,然后在包含 PDF 文件的目录下运行:

    bash 复制代码
    python convert_pdf_to_png.py
  3. 结果保存:

    所有生成的 PNG 文件将保存到当前目录下的 pdf_to_png_output 文件夹中。

如果需要修改 DPI(影响图像质量),可以调整脚本中的 DPI 变量值。

相关推荐
winfredzhang4 分钟前
Python 实战:用 wxPython 写一个 MD5 文件查重清理工具
python·sqlite·json·wxpython·md5·预览·查重
装不满的克莱因瓶8 分钟前
了解不同机器学习模型的分类
人工智能·python·算法·机器学习·ai·分类·数据挖掘
小江的记录本27 分钟前
【Spring全家桶】Spring Cloud 2023.0.x:配置中心:Nacos Config、Apollo(附《思维导图》+《面试高频考点清单》)
java·spring boot·后端·python·spring·spring cloud·面试
华大哥1 小时前
spring boot 和php 调用 LibreOffice 转换 Excel 到 PDF 完整实现
java·pdf·excel
财经资讯数据_灵砚智能1 小时前
基于全球经济类多源新闻的NLP情感分析与数据可视化(日间)2026年6月7日
人工智能·python·ai·信息可视化·自然语言处理·ai编程·灵砚智能
smith成长之旅1 小时前
08 | Mem0 框架分析: BM25 的 Sigmoid 归一化
数据库·python·算法
DogDaoDao1 小时前
【第 04 篇】列表与元组 —— 序列类型核心详解
人工智能·python·深度学习·神经网络·机器学习·conda·numpy
idingzhi1 小时前
A股量化策略日报(2026年06月07日)
python
xingpanvip1 小时前
使用 Webwright 在 CSDN 自动发文:Python 浏览器自动化实践
开发语言·python·自动化
armwind1 小时前
openISP学习7-CCM — Color Correction Matrix(色彩校正矩阵)
python·学习·矩阵