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();
        }
    }
}
相关推荐
丹牛Daniel10 分钟前
Java解决HV000183: Unable to initialize ‘javax.el.ExpressionFactory‘
java·开发语言·spring boot·tomcat·intellij-idea·个人开发
消失的旧时光-194328 分钟前
智能指针(三):实现篇 —— shared_ptr 的内部设计与引用计数机制
java·c++·c·shared_ptr
芒克芒克32 分钟前
深入浅出CopyOnWriteArrayList
java
wuqingshun31415942 分钟前
说一下java的反射机制
java·开发语言·jvm
A懿轩A1 小时前
【Java 基础编程】Java 异常处理保姆级教程:try-catch-finally、throw/throws、自定义异常
java·开发语言·python
极客先躯1 小时前
高级java每日一道面试题-2025年7月14日-基础篇[LangChain4j]-如何集成开源模型(如 Llama、Mistral)?需要什么基础设施?
java·langchain·存储·计算资源·模型服务框架·网络 / 协议·java 依赖
黎雁·泠崖1 小时前
Java 包装类:基本类型与引用类型的桥梁详解
java·开发语言
盖头盖2 小时前
【Java反序列化基础】
java
极客先躯2 小时前
高级java每日一道面试题-2025年7月15日-基础篇[LangChain4j]-如何集成国产大模型(如通义千问、文心一言、智谱 AI)?
java·人工智能·langchain·文心一言·异常处理·密钥管理·参数调优
追随者永远是胜利者3 小时前
(LeetCode-Hot100)226. 翻转二叉树
java·算法·leetcode·职场和发展·go