引用Apache工具包:
org.apache.pdfbox pdfbox2.0.26
public static byte[] pdfToImage2(byte[] pdfBytes) {
try {
PDDocument doc = PDDocument.load(pdfBytes);
int pageCount = doc.getNumberOfPages();
log.info("PDF转图片流,总页数:{}", pageCount);
PDFRenderer pdfRenderer = new PDFRenderer(doc);
// 不知道图片的宽和高,所以先定义个null
BufferedImage pdfImage = null;
// pdf有多少页
int y = 0;
List list = new ArrayList<>(pageCount);
// 所有页高度综合
int totalHeight = 0;
if(pageCount > 0){
for (int i = 0; i < pageCount; i++) {
// 每页pdf内容
BufferedImage bim = pdfRenderer.renderImageWithDPI(i, DEFAULT_DPI, ImageType.RGB);
totalHeight += bim.getHeight();
list.add(bim);
}
}
for (BufferedImage bim : list) {
// 如果是第一页需要初始化 BufferedImage
if (Objects.isNull(pdfImage)) {
// 创建一个总高、总宽 的图片缓冲区
pdfImage = new BufferedImage(bim.getWidth(), totalHeight, BufferedImage.TYPE_INT_RGB);
}
// 将每页pdf画到总的pdfImage上,x坐标=0,y坐标=之前所有页的高度和,属于向下偏移
pdfImage.getGraphics().drawImage(bim, 0, y, null);
y += bim.getHeight();
}
doc.close();
if(pdfImage != null){
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ImageIO.write(pdfImage, "jpg", baos);
baos.flush();
byte[] imageInByte = baos.toByteArray();
log.info("PDF转图片流成功");
return imageInByte;
}
return null;
} catch (Exception e) {
log.error("PDF转图片流失败:{}",e.getMessage());
return null;
}
}
// 测试代码
public static void main(String[] args) throws IOException {
String pdf = "pdfTemp.pdf";
String saveImgPath = "tempImg.jpg";
Path pdfPath = Paths.get( pdf);
byte[] bytes = Files.readAllBytes(pdfPath);
byte[] data = pdfToImage2(bytes);
File file = new File(saveImgPath);
//打开输入流
FileImageOutputStream imageOutput = new FileImageOutputStream(file);
//将byte写入硬盘
imageOutput.write(data, 0, data.length);
imageOutput.flush();;
imageOutput.close();
}



