当前位置:   article > 正文

使用freemarker和itextpdf结合,将html转化为pdf

使用freemarker和itextpdf结合,将html转化为pdf

工作中遇到模板中的html,需要转化成pdf作为附件上传到系统

于是经过研究分析,得出用freemarker和itextpdf结合

maven需要导入包:

  1. <dependency>
  2. <groupId>org.springframework.boot</groupId>
  3. <artifactId>spring-boot-starter-freemarker</artifactId>
  4. </dependency>
  5. <dependency>
  6. <groupId>com.itextpdf</groupId>
  7. <artifactId>itextpdf</artifactId>
  8. <version>${itextpdf.version}</version>
  9. </dependency>
  10. <dependency>
  11. <groupId>com.itextpdf.tool</groupId>
  12. <artifactId>xmlworker</artifactId>
  13. <version>5.5.8</version>
  14. </dependency>
  15. <dependency>
  16. <groupId>com.itextpdf</groupId>
  17. <artifactId>itext-asian</artifactId>
  18. <version>5.2.0</version>
  19. </dependency>

新建FreemarkerUtils工具类

  1. package com.example.common.util;
  2. import cn.hutool.core.util.StrUtil;
  3. import com.itextpdf.text.*;
  4. import com.itextpdf.text.pdf.BaseFont;
  5. import com.itextpdf.text.pdf.PdfWriter;
  6. import com.itextpdf.tool.xml.XMLWorkerFontProvider;
  7. import freemarker.core.HTMLOutputFormat;
  8. import freemarker.template.Configuration;
  9. import freemarker.template.Template;
  10. import lombok.extern.slf4j.Slf4j;
  11. import org.springframework.stereotype.Component;
  12. import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;
  13. import javax.annotation.Resource;
  14. import java.io.*;
  15. import java.nio.charset.Charset;
  16. import java.nio.charset.StandardCharsets;
  17. import java.nio.file.Files;
  18. import java.nio.file.Paths;
  19. import java.util.Map;
  20. import com.itextpdf.tool.xml.XMLWorkerHelper;
  21. @Component
  22. @Slf4j
  23. public class FreemarkerUtils {
  24. @Resource
  25. private Configuration stringConfiguration;
  26. private static final String FONT = "fonts/simhei.ttf";
  27. /**
  28. * 根据模板构建
  29. * @param content 模板内容
  30. * @param dataModel 模板数据
  31. **/
  32. public String buildByTemplate(String content, Map<String,Object> dataModel){
  33. return buildByTemplate(content, dataModel, StrUtil.EMPTY);
  34. }
  35. /**
  36. * 根据模板替换变量,得到变量替换后的内容
  37. * @param content 模板内容
  38. * @param dataModel 模板数据
  39. * @param defaultString 构建失败返回的默认值
  40. **/
  41. public String buildByTemplate(String content, Map<String,Object> dataModel,String defaultString) {
  42. try {
  43. // stringConfiguration.setOutputFormat(HTMLOutputFormat.INSTANCE);
  44. return FreeMarkerTemplateUtils.processTemplateIntoString(new Template("", content, stringConfiguration),
  45. dataModel);
  46. }catch (Exception e){
  47. log.warn("解析模板失败", e);
  48. }
  49. return defaultString;
  50. }
  51. public void htmlToPdf(String content) {
  52. // 创建一个Document对象
  53. Document document = new Document();
  54. try {
  55. // 创建一个PdfWriter实例来写PDF文件
  56. PdfWriter writer = PdfWriter.getInstance(document, Files.newOutputStream(Paths.get("E:\\张三测试.pdf")));
  57. // 打开文档
  58. document.open();
  59. InputStream inputStream = new ByteArrayInputStream(content.getBytes(StandardCharsets.UTF_8));
  60. FontProviderUtil fontProviderUtil = new FontProviderUtil();
  61. // 读取HTML文件并将其转换为PDF
  62. XMLWorkerHelper.getInstance().parseXHtml(writer, document,inputStream, null, StandardCharsets.UTF_8, fontProviderUtil);
  63. // 关闭文档
  64. document.close();
  65. } catch (DocumentException | IOException e) {
  66. e.printStackTrace();
  67. }
  68. }
  69. }

 解决中文乱码和生成的pdf中文不显示问题

  1. package com.example.common.util;
  2. import com.itextpdf.text.BaseColor;
  3. import com.itextpdf.text.Font;
  4. import com.itextpdf.text.pdf.BaseFont;
  5. import com.itextpdf.tool.xml.XMLWorkerFontProvider;
  6. import lombok.extern.slf4j.Slf4j;
  7. /**
  8. * 字体
  9. */
  10. @Slf4j
  11. public class FontProviderUtil extends XMLWorkerFontProvider {
  12. /**
  13. * 黑体 常规
  14. **/
  15. public static final String SIMHEI_TTF = "fonts/simhei.ttf";
  16. /**
  17. * 解决乱码和中文在pdf不显示问题
  18. * @param fontname the name of the font
  19. * @param encoding the encoding of the font
  20. * @param embedded true if the font is to be embedded in the PDF
  21. * @param size the size of this font
  22. * @param style the style of this font
  23. * @param color the <CODE>BaseColor</CODE> of this font.
  24. * @param cached true if the font comes from the cache or is added to
  25. * the cache if new, false if the font is always created new
  26. * @return
  27. */
  28. @Override
  29. public Font getFont(String fontname, String encoding, boolean embedded, float size, int style, BaseColor color, boolean cached) {
  30. BaseFont bf = null;
  31. try {
  32. bf = BaseFont.createFont(SIMHEI_TTF, BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
  33. } catch (Exception e) {
  34. log.info(e.getMessage());
  35. e.printStackTrace();
  36. }
  37. Font font = new Font(bf, size, style, color);
  38. font.setColor(color);
  39. return font;
  40. }
  41. }

在业务层调用即可

  freemarkerUtils.htmlToPdf(content);

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/思考机器4/article/detail/62720
推荐阅读
相关标签
  

闽ICP备14008679号