Use Itext7 + thymeleaf achieve html to PDF functions

Use Itext7 + thymeleaf achieve html to PDF functions

Program:

  1: import dependencies

  2: Prepare the path of the font, the exported file, written in html template Thymeleaf

  3: Set the font, character set

  4: Setting the html template parameter passed Thymeleaf

  5: create a pdf file in the export directory

  6: Convert html elements to PDF

    [Maven: com.itextpdf:layout:7.1.7]

      com.itextpdf.layout.font.FontProvider ### support custom fonts, Chinese and bold (need to use the English name is introduced fonts)

      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 ### set properties, including fonts, character sets, etc.

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

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

      org.thymeleaf.context.Context ### html template set the parameters of the incoming Thymeleaf

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

    Creating a PDF file and convert PDF to html element in

    [Maven: com.itextpdf:layout:7.1.7]

      com.itextpdf.layout.Document ### Create PDF document object

    [Maven: com.itextpdf:html2pdf:2.1.5]

      com.itextpdf.html2pdf.HtmlConverter ### html converter html-> pdf

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

      org.thymeleaf.ThmplateEngine ### thymeleaf template engine class, html template into a 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 (); Close document flow

 

Guess you like

Origin www.cnblogs.com/erfsfj-dbc/p/11760465.html