Java实现pdf转图片

第一步

复制代码
 <dependency>
        <groupId>org.apache.pdfbox</groupId>
        <artifactId>pdfbox</artifactId>
        <version>2.0.32</version> <!-- 请检查最新版本 -->
</dependency>

第二步

java 复制代码
package com.example.demo.file.pdf;

import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.rendering.ImageType;
import org.apache.pdfbox.rendering.PDFRenderer;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

public class PdfToImageConverter {
    public static void main(String[] args) {
        String pdfFilePath = "C:\\Users\\EDY\\Desktop\\output\\output.pdf"; // PDF文件路径
        String outputDirectory = "C:\\Users\\EDY\\Desktop\\directory"; // 输出目录路径

        convertPdfToImages(pdfFilePath, outputDirectory);
    }

    public static void convertPdfToImages(String pdfFilePath, String outputDirectory) {
        try (PDDocument document = PDDocument.load(new File(pdfFilePath))) {
            PDFRenderer renderer = new PDFRenderer(document);
            File outputDir = new File(outputDirectory);

            // 确保输出目录存在
            if (!outputDir.exists() && !outputDir.mkdirs()) {
                throw new IOException("Unable to create output directory: " + outputDirectory);
            }

            for (int page = 0; page < document.getNumberOfPages(); ++page) {
                BufferedImage bim = renderer.renderImageWithDPI(page, 300, ImageType.RGB);
                String fileName = "page_" + (page + 1) + ".png";
                File outputFile = new File(outputDir, fileName);
                ImageIO.write(bim, "PNG", outputFile);
            }
            System.out.println("Picture created successfully!");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
相关推荐
心之伊始7 小时前
Java 后端接入大模型:从 Token、并发到推理成本的完整估算方法
java·spring boot·性能优化·大模型·llm
BlackTurn8 小时前
技术经理投标
java
YG亲测源码屋8 小时前
java配置环境变量、jdk环境变量配置、java环境变量设置方法
java·开发语言
MIUMIUKK8 小时前
从语法层面,看懂 Python 的特殊处
java·开发语言·python
hujinyuan201608 小时前
2026年3月 中国电子学会青少年软件编程(Python)三级考试试卷 真题及答案
java·python·算法
basketball6169 小时前
C++ 高级编程:2. 基本线程池实现
java·开发语言·c++
MageGojo9 小时前
天气 API 接入实战:基于 ApiZero 实现实时天气、分钟级降水和 15 天预报查询
java·后端·spring·api 接口接入·接口实战
自动跟随9 小时前
UWB自动跟随技术全栈解析:从定位算法到“位控一体化“
java·网络·人工智能
喜欢打篮球的普通人9 小时前
LLVM 后端流程与关键数据结构:从 IR 到机器码的入门笔记
java·数据结构·笔记
弹简特9 小时前
【Java项目-轻聊】07-实现主页面模块
java·开发语言