第一步
<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();
}
}
}
本站资源均来自互联网,仅供研究学习,禁止违法使用和商用,产生法律纠纷本站概不负责!如果侵犯了您的权益请与我们联系!
转载请注明出处: 免费源码网-免费的源码资源网站 » Java实现pdf转图片
发表评论 取消回复