1、maven工程添加依赖
<!-- https://mvnrepository.com/artifact/commons-logging/commons-logging -->
<dependency>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
<version>1.2</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.pdfbox/pdfbox -->
<dependency>
<groupId>org.apache.pdfbox</groupId>
<artifactId>pdfbox</artifactId>
<version>2.0.21</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.pdfbox/fontbox -->
<dependency>
<groupId>org.apache.pdfbox</groupId>
<artifactId>fontbox</artifactId>
<version>2.0.20</version>
</dependency>
注:如果测试需要jar包,https://mvnrepository.com/artifact/org.apache.pdfbox/fontbox/2.0.20 搜索下载。
2、代码
package com.hysoft;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.rendering.PDFRenderer;
public class pdfUtil {
public static void main(String[] args) {
pdf2Image("D:\\Desktop\\pdftest\\2020年.pdf", "D:\\Desktop\\pdftest\\", 200);
}
//PDF转图片的方法 for那里看看是几张图片。 几页。根据页数进行转
/***
* PDF文件转PNG图片,全部页数
*
* @param PdfFilePath pdf完整路径
* @param dstImagFolder 图片生成路径
* @param dpi dpi越大转换后越清晰,相对转换速度越慢
* @return
*/
public static String pdf2Image(String PdfFilePath, String dstImgFolder, int dpi) {
System.out.println("开始转换");
File file = new File(PdfFilePath);
PDDocument pdDocument;
try {
String imgPDFPath = file.getParent();
int dot = file.getName().lastIndexOf('.');
String imagePDFName = file.getName().substring(0, dot); // 获取图片文件名
String imgFolderPath = dstImgFolder;
pdDocument = PDDocument.load(file);
int pageNum = pdDocument.getNumberOfPages();
PDFRenderer renderer = new PDFRenderer(pdDocument);
/* dpi越大转换后越清晰,相对转换速度越慢 */
StringBuffer imgFilePath = null;
for (int i = 0; i < pageNum; i++) {
String imgFilePathPrefix = imgFolderPath + File.separator + imagePDFName + i;
imgFilePath = new StringBuffer();
imgFilePath.append(imgFilePathPrefix);
imgFilePath.append(".png");
File dstFile = new File(imgFilePath.toString());
BufferedImage image = renderer.renderImageWithDPI(i, dpi);
ImageIO.write(image, "png", dstFile);
}
System.out.println("PDF文档转PNG图片成功!");
return imgFilePath.toString();
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
}