栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

java将PDF文件多页转图片流

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

java将PDF文件多页转图片流

引用Apache工具包:


  org.apache.pdfbox
  pdfbox
  2.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();
    }

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/933074.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号