java - 在 java 中使用 thymleaf html 模板下载 pdf 文件时,css 样式不可见
问题描述
我正在使用 thymleaf html 模板。当我预览页面时,样式看起来不错。当我下载 pdf 时,我没有看到应用了任何 CSS 样式。pdf 仅包含内容而不是我应用的样式。
// 下载生成代码
我引用并使用相同的Pdf 生成代码链接
// 示例代码
<!DOCTYPE HTML>
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8"></meta>
<title>Profile Preview</title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/normalize/7.0.0/normalize.min.css"></link>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/paper-css/0.4.1/paper.css"></link>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css"></link>
<style>
@page { size: A4 }
table {
border-collapse: collapse;
width: 100%;
margin-bottom: 20px;
}
td, th {
border: 1px solid #dddddd;
text-align: left;
padding: 5px;
}
tr:nth-child(even) {
background-color: #dddddd
}
</style>
</head>
<body class="A4">
<div class ="preview">
<section class="sheet">
<div class="logo">
<img th:src="@{/images/logo.png}" />
</div>
<h4 style="font-size: 1em; font-weight: bold; line-height: 1em">
<p>Age: <span th:text="${profile.basicInfo.age}"></span></p>
<p>D.O.B: <span th:text="${profile.basicInfo.birthDate}"></span></p>
<p>Gender: <span th:text="${profile.basicInfo.gender.toString()}"></span></p>
<p>Education: <span th:text="${profile.professionalInfo.educationDetail}"></span></p>
</h4>
<table>
<tr>
<th colspan="4" style="text-align:center; background-color: #6c3c81; color:white; font-weight: bold">Partner Preference Information</th>
</tr>
</table>
</div>
</section>
</div>
<button class="button" onClick="window.print();this.style.display='none'">Print</button>
</body>
</html>
// 服务器端代码
GetMapping("/{id}/download")
public void download(@PathVariable("id") String id, HttpServletResponse response) {
try {
Path file = Paths.get(profilePdfService.generatePdf(id).getAbsolutePath());
if (Files.exists(file)) {
response.setContentType("application/pdf");
response.addHeader("Content-Disposition", "attachment; filename=" + file.getFileName());
Files.copy(file, response.getOutputStream());
response.getOutputStream().flush();
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
解决方案
您似乎正在使用 Flying Saucer 以 PDF 格式呈现生成的 Thymeleaf 模板 HTML。
这里可能有几个问题。
首先,您需要向 Flying Source 提供适当的 XHTML 文档。对于这个任务,您可以使用 JTidy 将呈现的 Thymeleaf 模板转换为 XHTML:它可能不适用于非常复杂的 HTML,但很可能在您的用例中会起作用。
JTidy 有很多版本。抱歉,在以前版本的答案中,我为您提供了对我以前使用的过时版本的参考,这可能不适用于您需要的 HTML5。请根据一个全新的 JTidy项目使用以下依赖项:
<dependency>
<groupId>com.github.jtidy</groupId>
<artifactId>jtidy</artifactId>
<version>1.0.2</version>
</dependency>
例如,在PdfService
你在问题中指出的类的源代码中,修改generatePdf
方法如下:
public File generatePdf() throws IOException, DocumentException {
Context context = getContext();
String html = loadAndFillTemplate(context);
String xhtml = convertToXhtml(html);
return renderPdf(xhtml);
}
看起来像哪里convertToXhtml
(是适用于新 JTidy 库版本的先前版本的更新版本):
// Necessary imports, among others
import org.w3c.dom.Document;
import org.w3c.tidy.Tidy;
//...
private String convertToXhtml(String html) throws UnsupportedEncodingException {
Tidy tidy = new Tidy();
tidy.setXHTML(true);
tidy.setIndentContent(true);
tidy.setPrintBodyOnly(true);
tidy.setInputEncoding("UTF-8");
tidy.setOutputEncoding("UTF-8");
tidy.setSmartIndent(true);
tidy.setShowWarnings(false);
tidy.setQuiet(true);
tidy.setTidyMark(false);
Document htmlDOM = tidy.parseDOM(new ByteArrayInputStream(html.getBytes()), null);
OutputStream out = new ByteArrayOutputStream();
tidy.pprint(htmlDOM, out);
return out.toString();
}
查看执行此过程后页面的外观:您应用了很多内联样式,PDF 应该看起来更好。
此外,不要使用外部 CDN 分布式样式表,而是使用它们的本地副本,您的应用程序可以将其作为PDF_RESOURCES
在PdfService
类的源代码中标识的资源来访问。
正如您在该类的实现中看到renderPdf
的那样,它被用作查找页面中引用的不同资源的基本 URL。
最后,注意您的徽标:也许您需要为此目的提供一些ReplacedElementFactory的自定义实现。请考虑阅读this或this other SO questions,我认为它们会有所帮助。
按照这些步骤,稍作调整,您应该能够获得类似于以下 PDF 的内容:
如果 Flying Saucer 不能满足您的要求,请查看任何无头浏览器,例如PhantomJS来执行转换。
推荐阅读
- python - 如何使用python分离视频和音频
- reactjs - 在 Next.js 中使用 createPortal 时出现“目标容器不是 DOM 元素”错误
- amazon-web-services - 如何使用 SPINNAKER 将服务从一个池迁移到 PCF 中的另一个池?
- logging - 标准化开放遥测日志格式
- java - 加入字符串而不连接它
- javascript - 成功发送邮件后如何重置我的联系表?
- python - Python Pylab linspace 导入顺序问题?
- python - 如何使用 matplotlib python 在烛台图表中显示小时和分钟 - 时间
- react-native - 深色主题不适用于我在 Android 11 上的 React 本机应用
- vba - 在 MSWord 中使用 VBA 搜索文件