当前位置: 首页 > news >正文

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

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

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)。

    conda install pdf2image
    

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

    • Windows:下载 Poppler 的二进制文件并将其添加到系统 PATH。
    • macOS:通过 brew install poppler 安装。
    • Linux:通过 apt install poppler-utils 安装。
  2. 运行脚本:
    将脚本保存为 convert_pdf_to_png.py,然后在包含 PDF 文件的目录下运行:

    python convert_pdf_to_png.py
    
  3. 结果保存:
    所有生成的 PNG 文件将保存到当前目录下的 pdf_to_png_output 文件夹中。

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

http://www.lryc.cn/news/487820.html

相关文章:

  • 解决 Spring Boot 中 `Ambiguous mapping. Cannot map ‘xxxController‘ method` 错误
  • C++ 函数返回值优化
  • c++源码阅读__ThreadPool__正文阅读
  • 关于ES的查询
  • 数据结构初识
  • 保存数据到Oracle时报错ORA-17004: 列类型无效: 1111
  • Excel——宏教程(1)
  • 论文浅尝 | MindMap:知识图谱提示激发大型语言模型中的思维图(ACL2024)
  • 第6章:TDengine 标签索引和删除数据
  • 【微软:多模态基础模型】(5)多模态大模型:通过LLM训练
  • 海外带云仓多语言商城源码,多语言多商家云仓一键代发商城
  • android:taskAffinity 对Activity退出时跳转的影响
  • Apache Dolphinscheduler数据质量源码分析
  • solana链上智能合约开发案例一则
  • 使用 PyTorch 实现 ZFNet 进行 MNIST 图像分类
  • 车轮上的科技:Spring Boot汽车新闻集散地
  • IDEA2023 SpringBoot整合Web开发(二)
  • 国产三维CAD 2025新动向:推进MBD模式,联通企业设计-制造数据
  • ubuntu 之 安装mysql8
  • Flink Lookup Join(维表 Join)
  • Elasticsearch retrievers 通常与 Elasticsearch 8.16.0 一起正式发布!
  • 【并发模式】Go 常见并发模式实现Runner、Pool、Work
  • 【前端知识】Javascript前端框架Vue入门
  • Springboot3.3.5 启动流程之 Bean创建流程
  • golang反射函数注册
  • 【Spring】Bean
  • 深入解析TK技术下视频音频不同步的成因与解决方案
  • 为什么要使用Ansible实现Linux管理自动化?
  • Android:任意层级树形控件(有效果图和Demo示例)
  • C++ 容器全面剖析:掌握 STL 的奥秘,从入门到高效编程