pdf转png工具类

pdf转图片的工具类

1、需要引入的包


        <dependency>
            <groupId>org.apache.pdfbox</groupId>
            <artifactId>pdfbox</artifactId>
            <version>2.0.4</version>
        </dependency>

2、工具类

public static void main(String[] args) {
    String path="D://test/21.pdf";
    String outpath="D://filesdata/21.png";
    pdfToImage(path,outpath);
}

public static List<String> pdfToImage(String path, String outpath) {
    int DPI = 130;
    try {
      Path pdfPath = Paths.get(path);
      byte[] bytes = Files.readAllBytes(pdfPath);
      PDDocument doc = PDDocument.load(bytes);
      int pageCount = doc.getNumberOfPages();
      /* log.info("PDF转图片流,总页数:{}", pageCount);*/
      PDFRenderer pdfRenderer = new PDFRenderer(doc);
      // 不知道图片的宽和高,所以先定义个null
      BufferedImage pdfImage = null;
      // pdf有多少页
      int y = 0;
      List<BufferedImage> list = new ArrayList<>(pageCount);
      // 所有页高度综合
      int totalHeight = 0;
      if (pageCount > 0) {
         for (int i = 0; i < pageCount; i++) {
            // 每页pdf内容
            BufferedImage bim = pdfRenderer.renderImageWithDPI(i, DPI, ImageType.RGB);
            totalHeight += bim.getHeight();
            list.add(bim);
          }
       }
       System.out.println(list.size());
       List<String> picList = new ArrayList<>();
       int i = 1;
       for (BufferedImage bim : list) {
         // 如果是第一页需要初始化 BufferedImage
         if (bim != null) {
            String out = outpath + i + ".png";
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            ImageIO.write(bim, "png", baos);
            baos.flush();
            byte[] imageInByte = baos.toByteArray();
            File file = new File(out);
            //打开输入流
            FileImageOutputStream imageOutput = new FileImageOutputStream(file);
            //将byte写入硬盘
            imageOutput.write(imageInByte, 0, imageInByte.length);
            imageOutput.flush();
            imageOutput.close();
            picList.add(out);
            i++;
         }
       }
       doc.close();
       return picList;
     } catch (Exception e) {
       return null;
     }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值