pdf转图片【java版实现】
•
Jave
一、引入依赖
引入需要导入到项目中的依赖,如下所示:
net.sf.cssbox
pdf2dom
1.7
org.apache.pdfbox
pdfbox
2.0.12
org.apache.pdfbox
pdfbox-tools
2.0.12
com.itextpdf
itextpdf
5.5.13
二.编写工具类
pdf转图片的工具类如下所示,直接拷贝到项目即可
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> pdfToImage(String fileAddress, String filename, String type) {
long startTime = System.currentTimeMillis();
List<Map> list = new ArrayList();
Map 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> maps = pdfToImage("D:\\tanzer\\template\\bwFckHotwork\\110100DW1646870094552236032", "FTEV动用明火审批表20230609192945", "jpg");
System.out.println(maps);
}
}
三.测试
执行工具类中的main方法就行,会将pdf文件转换成多张图片到同级目录中。
本文来自网络,不代表协通编程立场,如若转载,请注明出处:https://www.net2asp.com/c9f15c6c25.html
