• Java将获取的参数,图片以及pdf文件放入到word文档指定位置


    首先引入的依赖

    1. <dependency>
    2. <groupId>org.apache.poigroupId>
    3. <artifactId>poiartifactId>
    4. <version>4.1.2version>
    5. dependency>
    6. <dependency>
    7. <groupId>org.apache.poigroupId>
    8. <artifactId>poi-ooxmlartifactId>
    9. <version>4.1.2version>
    10. dependency>
    11. <dependency>
    12. <groupId>org.apache.poigroupId>
    13. <artifactId>poi-ooxml-schemasartifactId>
    14. <version>4.1.2version>
    15. dependency>
    16. <dependency>
    17. <groupId>org.apache.pdfboxgroupId>
    18. <artifactId>pdfboxartifactId>
    19. <version>2.0.27version>
    20. dependency>
    21. <dependency>
    22. <groupId>com.deepoovegroupId>
    23. <artifactId>poi-tlartifactId>
    24. <version>1.9.0version>
    25. dependency>

    接下面的是template.docx文档,参数是以{{paramName}}格式的,为什么要以这种格式,是因为下面的方法,在替换参数的时候需要

    XWPFTemplate template = XWPFTemplate.compile( "C:\\Users\\Administrator\\Desktop\\template.docx").render(jsonObject);

    但是从数据库获取的参数跟模板中的参数一一对应上即可,格式如下(我是json形式展示的):

    {
        "countQuota": "1",
        "noEmission": "1",
        "greenConsume": "1",
        "pollutCharge": "1",
        "emissionPermit": "C:\\Users\\Administrator\\Desktop\\",
        "capitalOutlay": "1",
        "carbonTarget": "1",
        "zeroEmissionPower": "",
        "kgce": "",
        "productStandard": "",
        "totalConsume": "",
        "carbonEmission": "",
        "consumePer": "",
        "fileNames": "1.png,2.jpg,3.pdf",
        "directEmission": "",
        "indirectEmission": "1",
        "partiEmission": "1"
    }

    template.docx文档

    大体上长这样

     这里主要给图片中4.15排污许可证那里插入文件

    具体代码如下:

    1. package com.example.threaddemo.test;
    2. import com.alibaba.excel.util.StringUtils;
    3. import com.alibaba.fastjson.JSONObject;
    4. import com.deepoove.poi.XWPFTemplate;
    5. import org.apache.pdfbox.pdmodel.PDDocument;
    6. import org.apache.pdfbox.rendering.PDFRenderer;
    7. import org.apache.poi.util.IOUtils;
    8. import org.apache.poi.util.Units;
    9. import org.apache.poi.xwpf.usermodel.*;
    10. import javax.imageio.ImageIO;
    11. import java.awt.image.BufferedImage;
    12. import java.io.*;
    13. import java.util.List;
    14. import java.util.Map;
    15. public class WordTest3 {
    16. public static void main(String[] args) throws Exception {
    17. String str = "{\n" +
    18. "\t\"countQuota\": \"1\",\n" +
    19. "\t\"noEmission\": \"1\",\n" +
    20. "\t\"greenConsume\": \"1\",\n" +
    21. "\t\"pollutCharge\": \"1\",\n" +
    22. "\t\"emissionPermit\": \"C:\\\\Users\\\\Administrator\\\\Desktop\\\\\",\n" +
    23. "\t\"capitalOutlay\": \"1\",\n" +
    24. "\t\"carbonTarget\": \"1\",\n" +
    25. "\t\"zeroEmissionPower\": \"\",\n" +
    26. "\t\"kgce\": \"\",\n" +
    27. "\t\"productStandard\": \"\",\n" +
    28. "\t\"totalConsume\": \"\",\n" +
    29. "\t\"carbonEmission\": \"\",\n" +
    30. "\t\"consumePer\": \"\",\n" +
    31. "\t\"fileNames\": \"1.png,2.jpg,滴滴电子发票.pdf\",\n" +
    32. "\t\"directEmission\": \"\",\n" +
    33. "\t\"indirectEmission\": \"1\",\n" +
    34. "\t\"partiEmission\": \"1\"\n" +
    35. "}";
    36. //str = str.replace("\n","");
    37. //str.replace("}","\"}");
    38. //str = str.replaceAll("\\\\667A", "667A");
    39. System.out.println("str = " + str);
    40. //Map jsonObject = JSONObject.parseObject(str, Map.class);
    41. JSONObject jsonObject = JSONObject.parseObject(str);
    42. //.render(jsonObject) json,map或者实体类都是可以的,只要参数能对上就可以了
    43. XWPFTemplate template = XWPFTemplate.compile( "C:\\Users\\Administrator\\Desktop\\generate-template.docx").render(jsonObject);
    44. template.write(new FileOutputStream("C:\\Users\\Administrator\\Desktop\\1.docx"));
    45. template.close();
    46. if (StringUtils.isNotBlank(jsonObject.getString("emissionPermit"))) {//说明排污许可证上传了
    47. XWPFDocument document = new XWPFDocument(new FileInputStream("C:\\Users\\Administrator\\Desktop\\1.docx"));
    48. // 获取文档中的表格列表
    49. List tables = document.getTables();
    50. String path_pre = jsonObject.getString("emissionPermit");
    51. String fileNames = jsonObject.getString("fileNames");
    52. // 遍历表格
    53. for (XWPFTable table : tables) {
    54. // 遍历表格的行
    55. List rows = table.getRows();
    56. for (XWPFTableRow row : rows) {
    57. // 遍历行的单元格
    58. List cells = row.getTableCells();
    59. for (XWPFTableCell cell : cells) {
    60. // 获取单元格的文本内容
    61. String cellText = cell.getText();
    62. if (cellText.contains(path_pre)) {
    63. XWPFRun run = cell.getParagraphs().get(0).getRuns().get(0);
    64. run.setText("", 0);//置空里面的参数{{emissionPermit}}
    65. for (String filename : fileNames.split(",")) {
    66. String file_path = path_pre + filename;
    67. System.out.println("file_path = " + file_path);
    68. // 加载Word文档
    69. if (file_path.endsWith(".png")) {
    70. int type = XWPFDocument.PICTURE_TYPE_PNG;
    71. insertImage(file_path, type, run, filename);
    72. }
    73. if (file_path.endsWith(".jpg")) {
    74. int type = XWPFDocument.PICTURE_TYPE_JPEG;
    75. insertImage(file_path, type, run, filename);
    76. }
    77. if (file_path.endsWith(".pdf")) {
    78. String newFilePath = file_path.replace(".pdf", ".png");
    79. convertPdfToImage(file_path, newFilePath);
    80. int type = XWPFDocument.PICTURE_TYPE_PNG;
    81. insertImage(newFilePath, type, run, filename);
    82. File newFile = new File(newFilePath);
    83. newFile.delete();//把pdf生成的png图片删除
    84. }
    85. }
    86. // 保存修改后的文档
    87. FileOutputStream outputStream1 = new FileOutputStream("C:\\Users\\Administrator\\Desktop\\1.docx");
    88. document.write(outputStream1);
    89. outputStream1.close();
    90. }
    91. }
    92. }
    93. }
    94. }
    95. //jsonObject.remove("emissionPermit");
    96. }
    97. //将pdf转为png
    98. private static void convertPdfToImage(String pdfPath, String imagePath) throws IOException {
    99. PDDocument document = PDDocument.load(new File(pdfPath));
    100. PDFRenderer renderer = new PDFRenderer(document);
    101. BufferedImage image = renderer.renderImage(0); // 渲染第一页为图像
    102. ImageIO.write(image, "PNG", new File(imagePath));
    103. document.close();
    104. }
    105. //将图片插入到指定位置
    106. private static void insertImage(String filePath, int type, XWPFRun run, String fileName) {
    107. try (InputStream pngInputStream = new FileInputStream(filePath)) {
    108. byte[] jpgBytes = IOUtils.toByteArray(pngInputStream);
    109. run.addPicture(new ByteArrayInputStream(jpgBytes), type, fileName, Units.toEMU(300), Units.toEMU(200));
    110. } catch (Exception e) {
    111. //LOGGER.info("tcfd插入图片异常,异常原因:",e.getMessage(),e);
    112. throw new RuntimeException(e);
    113. }
    114. }
    115. }

    在网上找了半天也么有什么好的方式可以在指定的位置直接将pdf插入进去,如果哪位大神有好的方式,可以留个言

    如果在运行的过程中有这个报错:java.lang.NoClassDefFoundError: org/apache/fontbox/cmap/CMapParser

    请加下下面的依赖

    1. <dependency>
    2. <groupId>org.apache.pdfboxgroupId>
    3. <artifactId>fontboxartifactId>
    4. <version>2.0.27version>
    5. dependency>

  • 相关阅读:
    Windows安装MongoDB
    C指针笔记
    Java中通过反射+自定义注解判断对象中部分属性是否为空,返回为空字段的名称或自定义含义
    Web前端—移动Web第四天(媒体查询、Bootstrap、综合案例-alloyTeam)
    【Leetcode每日一题】2022-09-30 面试题 01.08 零矩阵 Java实现
    LeetCode每日一题(2233. Maximum Product After K Increments)
    动规算法-地下城游戏
    Linux中设置开机启动执行命令和普通用户配置环境变量开机启动生效
    webpack性能优化——从产出代码角度优化(提升产品性能)
    Vue3 复制 copy 功能实现(vue-clipboard3)
  • 原文地址:https://blog.csdn.net/Java_mouse/article/details/131709157