public static List<String> pdfToImage(String pdfPath,int size) {
List<String> list = new ArrayList<>();
String imagePath;
try {
String fileName = pdfPath.substring(0, pdfPath.lastIndexOf("."));
//图像合并使用参数
// 总宽度
int width = 0;
// 保存一张图片中的RGB数据
int[] singleImgRGB;
int shiftHeight = 0;
//保存每张图片的像素值
BufferedImage imageResult = null;
//利用PdfBox生成图像
PDDocument pdDocument = PDDocument.load(new File(pdfPath));
PDFRenderer renderer = new PDFRenderer(pdDocument);
//循环每个页码
for (int i = 0, len = pdDocument.getNumberOfPages(); i < len; i++) {
if (i == size) {
break;
}
BufferedImage image = renderer.renderImageWithDPI(i, 105, ImageType.RGB);
int imageHeight = image.getHeight();
int imageWidth = image.getWidth();
//计算高度和偏移量
//使用第一张图片宽度;
width = imageWidth;
//保存每页图片的像素值
imageResult = new BufferedImage(width, imageHeight, BufferedImage.TYPE_INT_RGB);
//这里有高度,可以将imageHeight*len,我这里值提取一页所以不需要
singleImgRGB = image.getRGB(0, 0, width, imageHeight, null, 0, width);
// 写入流中
imageResult.setRGB(0, shiftHeight, width, imageHeight, singleImgRGB, 0, width);
File f = new File(fileName);
if (!f.exists()) {
f.mkdir();
}
imagePath = fileName + "/image" + i+1 + ".png";
File file = new File(imagePath);
if (!file.exists()) {
file.mkdir();
}
// 写图片
ImageIO.write(imageResult, "png", new File(imagePath));
list.add(imagePath);
}
pdDocument.close();
} catch (Exception e) {
e.printStackTrace();
}
return list;
//OVER
}