使用pdfbox 把pdf转成图片

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页数过多图片高度过大,会导致内存溢出

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值