一、引入依赖
引入需要导入到项目中的依赖,如下所示:
XML
<!-- pdf转图片 -->
<dependency>
<groupId>net.sf.cssbox</groupId>
<artifactId>pdf2dom</artifactId>
<version>1.7</version>
</dependency>
<dependency>
<groupId>org.apache.pdfbox</groupId>
<artifactId>pdfbox</artifactId>
<version>2.0.12</version>
</dependency>
<dependency>
<groupId>org.apache.pdfbox</groupId>
<artifactId>pdfbox-tools</artifactId>
<version>2.0.12</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.itextpdf/itextpdf -->
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>itextpdf</artifactId>
<version>5.5.13</version>
</dependency>
二.编写工具类
pdf转图片的工具类如下所示,直接拷贝到项目即可
java
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.rendering.PDFRenderer;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.*;
import java.util.*;
public class Pdf2Image {
/**
* 使用文件流整个pdf转换成图片
* @param fileAddress 文件地址 如:C:\\Users\\user\\Desktop\\test
* @param filename PDF文件名不带后缀名
* @param type 图片类型 png 、jpg
*/
public static List<Map<String, String>> pdfToImage(String fileAddress, String filename, String type) {
long startTime = System.currentTimeMillis();
List<Map<String, String>> list = new ArrayList<>();
Map<String, String> resultMap = null;
PDDocument pdDocument = null;
String fileName = null;
String imgPath = null;
try {
// 将文件地址和文件名拼接成路径 注意:线上环境不能使用\\拼接
File FilePath = new File(fileAddress + "/" + filename + ".pdf");
// 文件流
FileInputStream inputStream = new FileInputStream(FilePath);
int dpi = 296;
pdDocument = PDDocument.load(inputStream);
PDFRenderer renderer = new PDFRenderer(pdDocument);
int pageCount = pdDocument.getNumberOfPages();
/* dpi越大转换后越清晰,相对转换速度越慢 */
for (int i = 0; i < pageCount; i++) {
resultMap = new HashMap<>();
fileName = filename + "_" + (i + 1) + "." + type;
//注意:线上环境不能使用\\拼接
imgPath = fileAddress + "/" + fileName;
BufferedImage image = renderer.renderImageWithDPI(i, dpi);
ImageIO.write(image, type, new File(imgPath));
resultMap.put("fileName", fileName);
resultMap.put("filePath", imgPath); // 图片路径
list.add(resultMap);
}
long endTime = System.currentTimeMillis();
System.out.println("共耗时:" + ((endTime - startTime) / 1000.0) + "秒"); //转化用时
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
// 这里需要关闭PDDocument,不然如果想要删除pdf文件时会提示文件正在使用,无法删除的情况
pdDocument.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return list;
}
public static void main(String[] args) throws FileNotFoundException {
List<Map<String, String>> maps = pdfToImage("D:\\tanzer\\template\\bwFckHotwork\\110100DW1646870094552236032", "FTEV动用明火审批表20230609192945", "jpg");
System.out.println(maps);
}
}
三.测试
执行工具类中的main方法就行,会将pdf文件转换成多张图片到同级目录中。