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