public class PdfUtils {public static byte[] pdfToImage (byte[] bytes){BufferedImage pdfImage=null;try{PDDocument doc = PDDocument.load(bytes);PDFRenderer pdfRenderer = new PDFRenderer(doc);//获取总页数int pageCountNumberOfPages();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 = Page(i);PDRectangle cropBox = CropBox();int width =(int) Width();if(widthOne==0){widthOne=width;}//每页pdf内容BufferedImage bim = derImageWithDPI(i, 80, ImageType.RGB);totalHeight+Height();list.add(bim);}}for (BufferedImage bim : list) {//如果是第一页需要初始化if(Objects.isNull(pdfImage)){//创建一个总高、总宽的图片缓冲区pdfImage = new BufferedImage(widthOne, totalHeight, BufferedImage.TYPE_INT_RGB);}Graphics().drawImage(bim,0,y,null);y+Height();}doc.close();if(pdfImage!=null){ByteArrayOutputStream baos = new ByteArrayOutputStream();ImageIO.write(pdfImage,"png",baos);baos.flush();byte[] bytes1 = ByteArray();return bytes1;}return null;}catch ( Exception e){e.printStackTrace();}finally {if(pdfImage!=null){Graphics().dispose();}}return null;}
}
其中 new BufferedImage(widthOne, totalHeight, BufferedImage.TYPE_INT_RGB); 如果pdf页数过多图片高度过大,会导致内存溢出
本文发布于:2024-02-05 00:20:07,感谢您对本站的认可!
本文链接:https://www.4u4v.net/it/170719718761170.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
留言与评论(共有 0 条评论) |