• pdf转png工具类


    pdf转图片的工具类

    1、需要引入的包

    1. <dependency>
    2. <groupId>org.apache.pdfboxgroupId>
    3. <artifactId>pdfboxartifactId>
    4. <version>2.0.4version>
    5. dependency>

    2、工具类

    1. public static void main(String[] args) {
    2. String path="D://test/21.pdf";
    3. String outpath="D://filesdata/21.png";
    4. pdfToImage(path,outpath);
    5. }
    6. public static List pdfToImage(String path, String outpath) {
    7. int DPI = 130;
    8. try {
    9. Path pdfPath = Paths.get(path);
    10. byte[] bytes = Files.readAllBytes(pdfPath);
    11. PDDocument doc = PDDocument.load(bytes);
    12. int pageCount = doc.getNumberOfPages();
    13. /* log.info("PDF转图片流,总页数:{}", pageCount);*/
    14. PDFRenderer pdfRenderer = new PDFRenderer(doc);
    15. // 不知道图片的宽和高,所以先定义个null
    16. BufferedImage pdfImage = null;
    17. // pdf有多少页
    18. int y = 0;
    19. List list = new ArrayList<>(pageCount);
    20. // 所有页高度综合
    21. int totalHeight = 0;
    22. if (pageCount > 0) {
    23. for (int i = 0; i < pageCount; i++) {
    24. // 每页pdf内容
    25. BufferedImage bim = pdfRenderer.renderImageWithDPI(i, DPI, ImageType.RGB);
    26. totalHeight += bim.getHeight();
    27. list.add(bim);
    28. }
    29. }
    30. System.out.println(list.size());
    31. List picList = new ArrayList<>();
    32. int i = 1;
    33. for (BufferedImage bim : list) {
    34. // 如果是第一页需要初始化 BufferedImage
    35. if (bim != null) {
    36. String out = outpath + i + ".png";
    37. ByteArrayOutputStream baos = new ByteArrayOutputStream();
    38. ImageIO.write(bim, "png", baos);
    39. baos.flush();
    40. byte[] imageInByte = baos.toByteArray();
    41. File file = new File(out);
    42. //打开输入流
    43. FileImageOutputStream imageOutput = new FileImageOutputStream(file);
    44. //将byte写入硬盘
    45. imageOutput.write(imageInByte, 0, imageInByte.length);
    46. imageOutput.flush();
    47. imageOutput.close();
    48. picList.add(out);
    49. i++;
    50. }
    51. }
    52. doc.close();
    53. return picList;
    54. } catch (Exception e) {
    55. return null;
    56. }
    57. }

  • 相关阅读:
    Google 代码审查指南
    JVM将初始和最大内存大小设置为相同值的好处
    深度相机辅助导航避障(三):地面点云滤除
    HTML创建文本框的三种方式
    c++ 之安装opencv显示图片
    Spark 3.0 - 9.Ml 朴素贝叶斯中文分类分析与实战
    【AI基础】大模型资源整理
    Java技能树-网络-UDP-DatagramSocket
    【数据结构】谈谈ArrayList和LinkedList的区别
    如何使用PHP替换回车为br
  • 原文地址:https://blog.csdn.net/fraya1234/article/details/134524603