首先引入maven配置
<dependency>
<groupId>org.apache.pdfbox</groupId>
<artifactId>fontbox</artifactId>
<version>2.0.1</version>
</dependency>
<dependency>
<groupId>org.apache.pdfbox</groupId>
<artifactId>pdfbox</artifactId>
<version>2.0.1</version>
</dependency>
import org.apache.commons.collections.CollectionUtils;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.rendering.PDFRenderer;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import javax.imageio.ImageIO;
import lombok.extern.slf4j.Slf4j;
@Slf4j
public class PDFToImage {
public static void batchPic(List<BufferedImage> piclist, File response) {// 纵向处理图片
if (CollectionUtils.isEmpty(piclist)) {
log.error("图片数组为空!");
return;
}
try {
int height = 0; // 总高度
int width = 0; // 总宽度
int height1 = 0; // 临时的高度 , 或保存偏移高度
int height2 = 0; // 临时的高度,主要保存每个高度
int picNum = piclist.size();// 图片的数量
int[] heightArray = new int[picNum]; // 保存每个文件的高度
List<int[]> imgRGBList = new ArrayList<int[]>(); // 保存所有的图片的RGB
int[] imgRGB; // 保存一张图片中的RGB数据
for (int i = 0; i < picNum; i++) {
BufferedImage buffer = piclist.get(i);
heightArray[i] = height1 = buffer.getHeight();// 图片高度
if (i == 0) {
width = buffer.getWidth();// 图片宽度
}
height += height1; // 获取总高度
imgRGB = new int[width * height1];// 从图片中读取RGB
imgRGB = buffer.getRGB(0, 0, width, height1, imgRGB, 0, width);
imgRGBList.add(imgRGB);
}
height1 = 0; // 设置偏移高度为0
// 生成新图片
BufferedImage imageResult = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
for (int i = 0; i < picNum; i++) {
height2 = heightArray[i];
if (i != 0){
height1 += height2; // 计算偏移高度
}
imageResult.setRGB(0, height1, width, height2, imgRGBList.get(i), 0, width); // 写入流中
}
ImageIO.write(imageResult, "jpg", response);// 写图片
} catch (Exception e) {
log.error("生成图片异常",e);
}
}
public static void main(String[] args) throws Exception{
InputStream inputStream = new FileInputStream(new File("D:\\pdf\\test.pdf"));
PDDocument pdDocument = PDDocument.load(inputStream);
PDFRenderer renderer = new PDFRenderer(pdDocument);
/* dpi越大转换后越清晰,相对转换速度越慢 */
int pages = pdDocument.getNumberOfPages();
List <BufferedImage> piclist = new ArrayList <BufferedImage>();
for (int i = 0; i < pages; i++) {
BufferedImage image = renderer.renderImageWithDPI(i, 100);
piclist.add(image);
}
File file = new File("D:\\pdf\\test.png");
batchPic(piclist,file);
}
}