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();
        }
    }
}
相关推荐
以太浮标1 天前
华为eNSP模拟器综合实验之- AC+AP无线网络调优与高密场景
java·服务器·华为
Mr__Miss1 天前
JAVA面试-框架篇
java·spring·面试
小马爱打代码1 天前
SpringBoot:封装 starter
java·spring boot·后端
STARSpace88881 天前
SpringBoot 整合个推推送
java·spring boot·后端·消息推送·个推
码农幻想梦1 天前
实验八 获取请求参数及域对象共享数据
java·开发语言·servlet
a努力。1 天前
2026 AI 编程终极套装:Claude Code + Codex + Gemini CLI + Antigravity,四位一体实战指南!
java·开发语言·人工智能·分布式·python·面试
Dylan的码园1 天前
功能包介绍 : calendar
java·jvm·eclipse
二川bro1 天前
Java集合类框架的基本接口有哪些?
java·开发语言·python
菜鸟233号1 天前
力扣213 打家劫舍II java实现
java·数据结构·算法·leetcode
panzer_maus1 天前
Redis简单介绍(3)-持久化的实现
java·redis·mybatis