自学内容网 自学内容网

Java实现pdf转图片

第一步

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

第二步

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();
        }
    }
}


原文地址:https://blog.csdn.net/weixin_42923363/article/details/143476653

免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!