html模板
html
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>PDF Template</title>
</head>
<body>
<h1>User Information</h1>
<p>Name: <span th:text="${user.name}"></span></p>
[[${user.getName()}]]
[[${user.name}]]111
<p>Email: <span th:text="${user.email}"></span></p>
</body>
</html>
依赖
java
<!-- thymeleaf for html to pdf -->
<dependency>
<groupId>org.thymeleaf</groupId>
<artifactId>thymeleaf</artifactId>
<version>${org.thymeleaf.version}</version>
<scope>compile</scope>
</dependency>
PDFGenerator
java
import org.springframework.stereotype.Component;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;
import org.thymeleaf.templateresolver.ClassLoaderTemplateResolver;
import org.xhtmlrenderer.pdf.ITextRenderer;
import java.io.FileOutputStream;
import java.io.OutputStream;
@Component
public class PdfGenerator {
public PdfGenerator() {
}
public void generatePdfFromTemplate(User user, String templatePath, String outputPath) {
try (OutputStream outputStream = new FileOutputStream(outputPath)) {
Context context = new Context();
context.setVariable("user", user);
TemplateEngine templateEngine = new TemplateEngine();
// 创建并配置模板解析器
ClassLoaderTemplateResolver templateResolver = new ClassLoaderTemplateResolver();
templateResolver.setPrefix("templates/");
templateResolver.setSuffix(".html");
templateResolver.setTemplateMode("HTML");
// 将模板解析器设置到TemplateEngine中
templateEngine.setTemplateResolver(templateResolver);
String htmlContent = templateEngine.process(templatePath, context);
ITextRenderer renderer = new ITextRenderer();
renderer.setDocumentFromString(htmlContent);
renderer.layout();
renderer.createPDF(outputStream);
} catch (Exception e) {
e.printStackTrace();
}
}
}
使用
java
String templatePath = "template.html";
String outputPath = "C:\\Temp\\aaa\\2024\\3\\12\\output.pdf";
PdfGenerator pdfGenerator = new PdfGenerator();
pdfGenerator.generatePdfFromTemplate(User.builder().name("ss").email("22").build(), templatePath, outputPath);
导出成功
出现的问题:如果HTML文件里面有js就会失败