AbstractRender.java 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108
  1. package com.yaoyicloud.render;
  2. import java.io.ByteArrayInputStream;
  3. import java.io.IOException;
  4. import java.util.Map;
  5. import com.deepoove.poi.XWPFTemplate;
  6. import com.deepoove.poi.config.Configure;
  7. import com.deepoove.poi.config.ConfigureBuilder;
  8. import com.fasterxml.jackson.core.type.TypeReference;
  9. import com.fasterxml.jackson.databind.ObjectMapper;
  10. /**
  11. * 抽象渲染器
  12. *
  13. */
  14. public abstract class AbstractRender {
  15. /*
  16. * 导出文件位置
  17. */
  18. protected final String cwd;
  19. /*
  20. * Docx结果文件路径
  21. */
  22. protected String docxResultPath;
  23. /*
  24. * html结果文件路径
  25. */
  26. protected String htmlResultPath;
  27. /*
  28. * pdf结果文件路径
  29. */
  30. protected String pdfResultPath;
  31. public AbstractRender(String cwd) {
  32. this.cwd = cwd;
  33. }
  34. /**
  35. * Docx 渲染
  36. *
  37. * @param info 数据
  38. * @param templateFileContent 模板内容
  39. * @return 本地文件目录
  40. * @throws IOException
  41. */
  42. public final String renderDocx(String jsonStr, byte[] templateFileContent, String outputPath) throws IOException {
  43. // 注: 报告模板的模板变量按照json序列化的结果命名
  44. ObjectMapper objectMapper = new ObjectMapper();
  45. Map<String, Object> data = objectMapper.readValue(jsonStr, new TypeReference<Map<String, Object>>() {});
  46. ConfigureBuilder builder = Configure.builder();
  47. Configure config = builder.build();
  48. XWPFTemplate template =
  49. XWPFTemplate.compile(new ByteArrayInputStream(templateFileContent), config).render(data);
  50. template.writeToFile(outputPath);
  51. template.close();
  52. this.docxResultPath = outputPath;
  53. return this.docxResultPath;
  54. }
  55. /**
  56. * docx转换为pdf
  57. *
  58. * @return 本地文件目录
  59. * @throws IOException
  60. */
  61. public final String fromDocxToPdf() throws IOException {
  62. // 转换 docxResultPath 为 html
  63. // 加工html
  64. // 把 html 文件转成 pdf
  65. fromDocxToHtml();
  66. this.pdfResultPath = fromHtmlToPdf();
  67. return this.pdfResultPath;
  68. }
  69. /**
  70. * docx转换为Html
  71. *
  72. * @return 本地文件目录
  73. * @throws IOException
  74. */
  75. public final String fromDocxToHtml() throws IOException {
  76. // 转换 docxResultPath 为 html
  77. // 加工html
  78. this.htmlResultPath = cwd + "/1.html";
  79. return this.htmlResultPath;
  80. }
  81. /**
  82. * html转换为pdf
  83. *
  84. * @return 本地文件目录
  85. * @throws IOException
  86. */
  87. public final String fromHtmlToPdf() throws IOException {
  88. // 转换 htmlResultPath 为 pdf
  89. this.pdfResultPath = cwd + "/1.pdf";
  90. return this.pdfResultPath;
  91. }
  92. }