public class PdfUtils {
public static byte[] pdfToImage (byte[] bytes){
BufferedImage pdfImage=null;
try{
PDDocument doc = PDDocument.load(bytes);
PDFRenderer pdfRenderer = new PDFRenderer(doc);
//获取总页数
int pageCount=doc.getNumberOfPages();
int y=0;
List<BufferedImage> list = new ArrayList<>(pageCount);
int totalHeight=0;
int widthOne=0;
if(pageCount>0){
for (int i = 0; i < pageCount; i++) {
PDPage page = doc.getPage(i);
PDRectangle cropBox = page.getCropBox();
int width =(int) cropBox.getWidth();
if(widthOne==0){
widthOne=width;
}
//每页pdf内容
BufferedImage bim = pdfRenderer.renderImageWithDPI(i, 80, ImageType.RGB);
totalHeight+=bim.getHeight();
list.add(bim);
}
}
for (BufferedImage bim : list) {
//如果是第一页需要初始化
if(Objects.isNull(pdfImage)){
//创建一个总高、总宽的图片缓冲区
pdfImage = new BufferedImage(widthOne, totalHeight, BufferedImage.TYPE_INT_RGB);
}
pdfImage.getGraphics().drawImage(bim,0,y,null);
y+=bim.getHeight();
}
doc.close();
if(pdfImage!=null){
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ImageIO.write(pdfImage,"png",baos);
baos.flush();
byte[] bytes1 = baos.toByteArray();
return bytes1;
}
return null;
}catch ( Exception e){
e.printStackTrace();
}finally {
if(pdfImage!=null){
pdfImage.getGraphics().dispose();
}
}
return null;
}
}
其中 new BufferedImage(widthOne, totalHeight, BufferedImage.TYPE_INT_RGB); 如果pdf页数过多图片高度过大,会导致内存溢出