Before the article
Use Thymeleaf to render HTML dynamically
1. Add dependencies
<! --> <dependency> <groupId>com.itextpdf</ artifactId> <version>5.4.2</version> </dependency> <dependency> <groupId>org.xhtmlrenderer</groupId> <artifactId>core-renderer</artifactId> <version>R8</version> </dependency>Copy the code
2. Coding tool classes
import com.itextpdf.text.pdf.BaseFont; import com.lowagie.text.DocumentException; import org.springframework.stereotype.Component; import org.xhtmlrenderer.pdf.ITextFontResolver; import org.xhtmlrenderer.pdf.ITextRenderer; import java.io.IOException; import java.io.OutputStream; /** * Export PDF file conversion tool */ public class PDFUtil{/** * generate PDF file * @param out output stream * @param HTML HTML string * @throws IOException Ioexception * @throws DocumentException DocumentException */ public static void createPDF(OutputStream out, String html) throws IOException, DocumentException { ITextRenderer renderer = new ITextRenderer(); renderer.setDocumentFromString(html); FontResolver = renderer.getfontresolver (); fontResolver.addFont("pdf/font/fangsong.ttf", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED); fontResolver.addFont("pdf/font/PingFangSC.ttf", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED); renderer.layout(); renderer.createPDF(out); }}Copy the code
The font file is downloaded and added to the resouces path, which is modified accordingly
3. Effect demonstration
Problems encountered and solutions
Maven packages the source code, causing the content of the HTML file to be tampered with
- Cause: Placeholder ${} used by Maven plugin conflicts with Thymeleaf
- Workaround: Configure resource files in pom.xml without processing placeholders for HTML files when packaging
<build>
...
<resources>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
<excludes>
<exclude>**/*.html</exclude>
</excludes>
</resource>
<resource>
<directory>src/main/resources</directory>
<filtering>false</filtering>
<includes>
<include>**/*.html</include>
</includes>
</resource>
</resources>
</build>Copy the code
2, use Docker image, download the file error, lack of font processing class
- Use the image source Java :8 instead of OpenJDK :8-jre-alpine
© copyright belongs to the author, reprint or content cooperation please contact the author
● Service mesh-GRPC Local integrated remote Service
● Use Thymeleaf to render HTML dynamically
● Fastjson fatal flaw
● Spring Boot 2 integrates log4J2 logging framework
● Java interview key points summary set of core reference answers
● Java interview key points summary of the framework of reference answers
● How to protect your password
● Spring Boot RabbitMQ – Priority queue
This article is published by OpenWrite!