使用Itext7+thymeleaf 实现html转PDF功能


使用Itext7+thymeleaf 实现html转PDF功能

方案:

  1:导入依赖

  2:准备字体、导出文件的路径、写好Thymeleaf的html模板

  3:设置字体,字符集

  4:设置传入Thymeleaf的html模板参数

  5:在导出的目录下创建一个pdf文件

  6:将html元素转换到PDF中

    [Maven: com.itextpdf:layout:7.1.7]

      com.itextpdf.layout.font.FontProvider  ### 支持自定义字体,中文及加粗(引入字体时需要用英文名称)

      FontProvider fontProvider = new FontProvider();
      fontProvider.addFont(fontProvider.getClass().getClassLoader().getResource("font/simsun.ttf").getPath());
      fontProvider.addFont(fontProvider.getClass().getClassLoader().getResource("font/simhei.ttf").getPath());
      fontProvider.addStandardPdfFonts();

    [Maven: com.itextpdf:html2pdf:2.1.5]

      com.itextpdf.html2pdf.ConverterProperties ### 设置属性,包括字体,字符集等

      ConverterProperties converterProperties = new ConverterProperties();
      converterProperties.setFontProvider(fontProvider);
      converterProperties.setCharset("utf-8");

    [Maven: org.thymeleaf:thymeleaf:3.0.11.RELEASE]

      org.thymeleaf.context.Context ### 设置传入Thymeleaf的html模板参数

      Context ctx = new Context();
      ctx.setVariable("baseUrl", (String)extraMap.get("baseUrl"));

    创建一个PDF文件,并将html元素转换到PDF中

    [Maven: com.itextpdf:layout:7.1.7]

      com.itextpdf.layout.Document  ### 创建PDF文档对象

    [Maven: com.itextpdf:html2pdf:2.1.5]

      com.itextpdf.html2pdf.HtmlConverter   ### html转换器将html->pdf

    [Maven: org.thymeleaf:thymeleaf:3.0.11.RELEASE]

      org.thymeleaf.ThmplateEngine  ### thymeleaf模板引擎类,将html模板转化为String

    //中文Invoice
    File invoiceFileZh = new File("PDF路径.pdf");
    Document documentZh = new Document(new PdfDocument(new PdfWriter(new FileOutputStream(invoiceFileZh))), PageSize.A4);
    documentZh.setMargins(10, 20, 10, 20);//设置边距
    HtmlConverter.convertToElements(templateEngine.process("invoice/en.html", ctx), converterProperties)
            .stream().forEach(iElement -> documentZh.add((IBlockElement) iElement));
    documentZh.close(); 关闭文档流

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM