背景:
因一個特定的項目需要,將java對象內容以特定樣式的PDF格式輸出,查看了很多文檔,有收費的、免費的、基礎集成的。收費的工具就表現突出,免費的工具基本很難滿足需求,故著手采用基礎集成方案。過程中嘗試了很多中技術組合,最后根據個人調試效果選擇了"thymeleaf+htmltopdf"組合方案。
HTML轉PDF效果:
材料:
1、基礎JAVA環境
2、測試數據:
{"newspaper_name":"每日新聞","issue_number":"1024","issue_date":"2025年07月17日","editor_in_chief":"王主編","current_year":2025,"contact_info":{"address":"北京市朝陽區新聞大廈18層","phone":"010-12345678","email":"info@dailynews.com"},"headline_news":{"title":"國家發布新一代人工智能發展規劃","reporter":"張科技","time":"今天 08:15","image":"E:\\HtmlToPdf\\templates\\assets\\images\\headline.jpg","content":"\n <p>國務院近日印\r\n發《新一代人工智能發展規劃》,提出到2030年使中國人工智能理論、技術與應用總體達到世界領先水平,成為世界主要人工智能創新中心。</p>\n <p>規劃明 \r\n確了我國新一代人工智能發展的戰略目標:到2020年人工智能總體技術和應用與世界先進水平同步;到2025年人工智能基礎理論實現重大突破;到2030年人工智能理論、技術與應\r\n用總體達到世界領先水平。</p>\n <p>規劃還提出建立開放協同的人工智能科技創新體系,培育高端高效的智能經濟,建設安全便捷的智能社會等六大重點任務 \r\n。</p>\n "},"regular_news":[{"title":"本市地鐵新線路今日開通試運營","reporter":"李交通","time":"今天 07:30","image":"E:\\HtmlToPdf\\templates\\assets\\images\\subway.jpg","content":"\n <p>經過四年建設,本市地鐵14號線西段今日正式開通試運營。該線路全長16.5公里,設站8座,連\r\n接了多個商業區和居民區,將極大緩解西部城區的交通壓力。</p>\n <p>地鐵運營公司表示,試運營初期發車間隔為6分鐘,未來將根據客流情況逐步縮短間\r\n隔時間。首班車時間為5:30,末班車時間為23:00。</p>\n "},{"title":"夏季旅游旺季來臨 景區推出多項優惠","reporter":"趙旅游","time":"昨天 18:45","content":"\n <p>隨著暑期來臨,我市各大旅游景區迎來旅游旺季。為吸引游客,多家景區推出門票優惠活動。</p>\n <p>其\r\n中,著名5A級景區長城從即日起至8月31日,對全日制學生實行半價優惠;本市居民憑身份證可享受8折優惠。此外,多家景區還推出了夜游項目,豐富游客體驗。</p>\n \r\n "}],"special_report":{"title":"鄉村振興戰略實施五周年成果展","content":"\n <p>今年是鄉村振興戰略實施五周年。五年來,我市農村面貌\r\n發生顯著變化,農民收入持續增長,農業現代化水平明顯提高。</p>\n <p>據統計,五年來我市農村居民人均可支配收入年均增長8.5%,高于城鎮居民收入增速 \r\n;農村基礎設施顯著改善,所有行政村實現通硬化路、通寬帶;特色農業發展迅速,形成了一批知名農產品品牌。</p>\n <p>下一步,我市將重點推進鄉村產業 \r\n振興、人才振興、文化振興、生態振興和組織振興,讓農村成為安居樂業的美麗家園。</p>\n ","images":[{"url":"E:\\HtmlToPdf\\templates\\assets\\images\\country1.jpg","caption":"美麗鄉村建設成果"},{"url":"E:\\HtmlToPdf\\templates\\assets\\images\\country2.jpg","caption":"現代化農業大棚"},{"url":"E:\\HtmlToPdf\\templates\\assets\\images\\country3.jpg","caption":"鄉村旅游新業態"}]}}
制作:
1、在java項目的pom.xml中添加如下配置
<dependency><groupId>org.thymeleaf</groupId><artifactId>thymeleaf</artifactId><version>3.1.1.RELEASE</version></dependency><dependency><groupId>io.woo</groupId><artifactId>htmltopdf</artifactId><version>1.0.8</version><scope>compile</scope></dependency>
解釋:我們是利用thymeleaf 包進行java對象與HTML模板的賦值匹配
2、編寫thymeleaf 風格的HTML模板(如下,注意參數格式不是{{}},而是${})
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org" lang="zh-CN">
<head><meta charset="UTF-8"/><title th:text="${newspaper_name} + ' - ' + ${issue_date}">報紙名稱 - 日期</title></head>
<body><header class="newspaper-header"><div class="header-content"><h1 th:text="${newspaper_name}">報紙名稱</h1><div class="issue-info"><span>第 <span th:text="${issue_number}">期號</span> 期</span><span th:text="${issue_date}">日期</span><span>總編輯: <span th:text="${editor_in_chief}">總編輯姓名</span></span></div></div></header><main class="content-container"><!-- 頭條新聞 --><section class="headline-news"><h2 class="section-title">今日頭條</h2><article class="headline-article"><div class="headline-image"><img th:src="${headline_news.image}" th:alt="${headline_news.title}" src="placeholder.jpg"/></div><div class="headline-content"><h3 th:text="${headline_news.title}">頭條標題</h3><p class="news-meta"><span class="reporter">記者: <span th:text="${headline_news.reporter}">記者姓名</span></span><span class="publish-time" th:text="${headline_news.time}">發布時間</span></p><div class="news-content" th:utext="${headline_news.content}">頭條新聞內容</div></div></article></section><!-- 新聞列表 --><section class="news-list"><h2 class="section-title">新聞速遞</h2><article class="news-item" th:each="news : ${regular_news}"><h3 th:text="${news.title}">新聞標題</h3><p class="news-meta"><span class="reporter">記者: <span th:text="${news.reporter}">記者姓名</span></span><span class="publish-time" th:text="${news.time}">發布時間</span></p><div class="news-image" th:if="${news.image}"><img th:src="${news.image}" th:alt="${news.title}" src="placeholder.jpg"/></div><div class="news-content" th:utext="${news.content}">新聞內容</div></article></section><!-- 專題報道 --><section class="special-report" th:if="${special_report}"><h2 class="section-title">專題報道</h2><article class="special-article"><h3 th:text="${special_report.title}">專題標題</h3><div class="report-content" th:utext="${special_report.content}">專題內容</div><div class="report-gallery" th:if="${special_report.images}"><div class="gallery-item" th:each="image : ${special_report.images}"><img th:src="${image.url}" th:alt="${image.caption}" src="placeholder.jpg"/><p class="image-caption" th:text="${image.caption}">圖片說明</p></div></div></article></section></main><footer class="newspaper-footer"><p>地址: <span th:text="${contact_info.address}">地址</span> | 電話: <span th:text="${contact_info.phone}">電話</span> | 郵箱: <span th:text="${contact_info.email}">郵箱</span></p><p>版權所有 © <span th:text="${newspaper_name}">報紙名稱</span> <span th:text="${current_year}">年份</span></p></footer>
</body>
</html>
3、?模板對應的css樣式
/* 基礎樣式 */
body {font-family: "SimSun", "宋體", serif;line-height: 1.6;color: #333333;margin: 0;padding: 0;font-size: 14px;
}/* 報頭樣式 */
.newspaper-header {background-color: #8B0000;color: white;padding: 15px 0;text-align: center;border-bottom: 3px solid #DAA520;
}.header-content h1 {font-size: 36px;margin: 0;font-weight: bold;letter-spacing: 2px;
}.issue-info {margin-top: 10px;font-size: 14px;
}.issue-info span {margin: 0 10px;
}/* 內容容器 */
.content-container {padding: 20px;width: 1000px;margin: 0 auto;
}.section-title {font-size: 22px;border-bottom: 2px solid #8B0000;padding-bottom: 5px;color: #8B0000;margin: 25px 0 15px;
}/* 頭條新聞 */
.headline-news {margin-bottom: 30px;
}.headline-article {display: block;margin-top: 15px;overflow: hidden;
}.headline-image {float: left;width: 30%;margin-right: 20px;
}.headline-image img {width: 100%;height: auto;border: 1px solid #dddddd;
}.headline-content {float: left;width: 65%;
}.headline-content h3 {font-size: 20px;margin-top: 0;color: #222222;
}/* 常規新聞 */
.news-item {margin-bottom: 25px;padding-bottom: 15px;border-bottom: 1px dashed #cccccc;
}.news-item h3 {font-size: 18px;color: #444444;margin-bottom: 5px;
}.news-meta {color: #666666;font-size: 12px;margin: 5px 0;
}.news-meta span {margin-right: 15px;
}.news-image {margin: 10px 0;
}.news-image img {max-width: 100%;height: auto;border: 1px solid #dddddd;
}.news-content {text-align: justify;text-indent: 2em;
}/* 專題報道 */
.special-report {background-color: #f9f9f9;padding: 15px;margin-top: 30px;border: 1px solid #dddddd;
}.special-article h3 {font-size: 20px;color: #8B0000;text-align: center;
}.report-content {text-align: justify;margin: 15px 0;
}.report-gallery {display: block;margin: 20px 0;overflow: hidden;
}.gallery-item {float: left;width: 30%;margin-right: 3%;margin-bottom: 15px;
}.gallery-item img {width: 100%;height: auto;border: 1px solid #dddddd;
}.image-caption {font-size: 12px;color: #666666;text-align: center;margin-top: 5px;font-style: italic;
}/* 清除浮動 */
.clearfix:after {content: ".";display: block;height: 0;clear: both;visibility: hidden;
}/* 頁腳 */
.newspaper-footer {text-align: center;padding: 15px;background-color: #f5f5f5;font-size: 12px;color: #666666;border-top: 1px solid #dddddd;margin-top: 30px;
}
4、編寫PdfGenerator類
package com.powerbridge.pbplatformcarouteserver.utils;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Map;import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;
import org.thymeleaf.templateresolver.FileTemplateResolver;import cn.hutool.json.JSONUtil;
import io.woo.htmltopdf.HtmlToPdf;
import io.woo.htmltopdf.HtmlToPdfObject;public class PdfGenerator {private final String templateDir;private final TemplateEngine templateEngine;public PdfGenerator(String templateDir) {this.templateDir = templateDir.endsWith(File.separator) ? templateDir : templateDir + File.separator;this.templateEngine = initializeTemplateEngine();}private TemplateEngine initializeTemplateEngine() {FileTemplateResolver templateResolver = new FileTemplateResolver();templateResolver.setPrefix(this.templateDir);templateResolver.setSuffix(".html");templateResolver.setTemplateMode("HTML");templateResolver.setCharacterEncoding("UTF-8");templateResolver.setCacheable(false);TemplateEngine engine = new TemplateEngine();engine.setTemplateResolver(templateResolver);return engine;}public void generatePdfFromTemplate(String templateName,Map<String, Object> context,String outputPath,String[] cssFiles) throws IOException {// Process the template with ThymeleafContext thymeleafContext = new Context();thymeleafContext.setVariables(context);String processedTemplateName = templateName.endsWith(".html") ? templateName.substring(0, templateName.length() - 5) : templateName;String renderedHtml = templateEngine.process(processedTemplateName, thymeleafContext);// Generate PDFtry (OutputStream outputStream = new FileOutputStream(outputPath)) {
// ITextRenderer renderer = new ITextRenderer();Path basePath = Paths.get(templateDir).toAbsolutePath();// Add CSS if provided - CORRECTED APPROACHif (cssFiles != null) {for (String cssFile : cssFiles) {File css = new File(cssFile);if (css.exists()) {// Correct way to add CSS - embed it directly in the HTMLrenderedHtml = renderedHtml.replace("</head>", "<style type=\"text/css\">" +new String(Files.readAllBytes(css.toPath())) +"</style></head>");}}// Re-set the document with CSS includedSystem.out.println(renderedHtml);boolean success = HtmlToPdf.create().object(HtmlToPdfObject.forHtml(renderedHtml)).convert(outputPath);}} catch (Exception e) {throw new IOException("Failed to generate PDF: " + e.getMessage(), e);}}}
6、測試main函數
public static void main(String[] args) {try {String worksPath="E:/HtmlToPdf/";PdfGenerator generator = new PdfGenerator(worksPath);String context = "{\"newspaper_name\":\"每日新聞\",\"issue_number\":\"1024\",\"issue_date\":\"2025年07月17日\",\"editor_in_chief\":\"王主編\",\"current_year\":2025,\"contact_info\":{\"address\":\"北京市朝陽區新聞大廈18層\",\"phone\":\"010-12345678\",\"email\":\"info@dailynews.com\"},\"headline_news\":{\"title\":\"國家發布新一代人工智能發展規劃\",\"reporter\":\"張科技\",\"time\":\"今天 08:15\",\"image\":\"E:\\\\HtmlToPdf\\\\templates\\\\assets\\\\images\\\\headline.jpg\",\"content\":\"\\n <p>國務院近日印\\r\\n發《新一代人工智能發展規劃》,提出到2030年使中國人工智能理論、技術與應用總體達到世界領先水平,成為世界主要人工智能創新中心。</p>\\n <p>規劃明 \\r\\n確了我國新一代人工智能發展的戰略目標:到2020年人工智能總體技術和應用與世界先進水平同步;到2025年人工智能基礎理論實現重大突破;到2030年人工智能理論、技術與應\\r\\n用總體達到世界領先水平。</p>\\n <p>規劃還提出建立開放協同的人工智能科技創新體系,培育高端高效的智能經濟,建設安全便捷的智能社會等六大重點任務 \\r\\n。</p>\\n \"},\"regular_news\":[{\"title\":\"本市地鐵新線路今日開通試運營\",\"reporter\":\"李交通\",\"time\":\"今天 07:30\",\"image\":\"E:\\\\HtmlToPdf\\\\templates\\\\assets\\\\images\\\\subway.jpg\",\"content\":\"\\n <p>經過四年建設,本市地鐵14號線西段今日正式開通試運營。該線路全長16.5公里,設站8座,連\\r\\n接了多個商業區和居民區,將極大緩解西部城區的交通壓力。</p>\\n <p>地鐵運營公司表示,試運營初期發車間隔為6分鐘,未來將根據客流情況逐步縮短間\\r\\n隔時間。首班車時間為5:30,末班車時間為23:00。</p>\\n \"},{\"title\":\"夏季旅游旺季來臨 景區推出多項優惠\",\"reporter\":\"趙旅游\",\"time\":\"昨天 18:45\",\"content\":\"\\n <p>隨著暑期來臨,我市各大旅游景區迎來旅游旺季。為吸引游客,多家景區推出門票優惠活動。</p>\\n <p>其\\r\\n中,著名5A級景區長城從即日起至8月31日,對全日制學生實行半價優惠;本市居民憑身份證可享受8折優惠。此外,多家景區還推出了夜游項目,豐富游客體驗。</p>\\n \\r\\n \"}],\"special_report\":{\"title\":\"鄉村振興戰略實施五周年成果展\",\"content\":\"\\n <p>今年是鄉村振興戰略實施五周年。五年來,我市農村面貌\\r\\n發生顯著變化,農民收入持續增長,農業現代化水平明顯提高。</p>\\n <p>據統計,五年來我市農村居民人均可支配收入年均增長8.5%,高于城鎮居民收入增速 \\r\\n;農村基礎設施顯著改善,所有行政村實現通硬化路、通寬帶;特色農業發展迅速,形成了一批知名農產品品牌。</p>\\n <p>下一步,我市將重點推進鄉村產業 \\r\\n振興、人才振興、文化振興、生態振興和組織振興,讓農村成為安居樂業的美麗家園。</p>\\n \",\"images\":[{\"url\":\"E:\\\\HtmlToPdf\\\\templates\\\\assets\\\\images\\\\country1.jpg\",\"caption\":\"美麗鄉村建設成果\"},{\"url\":\"E:\\\\HtmlToPdf\\\\templates\\\\assets\\\\images\\\\country2.jpg\",\"caption\":\"現代化農業大棚\"},{\"url\":\"E:\\\\HtmlToPdf\\\\templates\\\\assets\\\\images\\\\country3.jpg\",\"caption\":\"鄉村旅游新業態\"}]}}";Map<String, Object> contextObj = JSONUtil.parseObj(context,true).toBean(Map.class,true);generator.generatePdfFromTemplate("templates/newsjava.html",contextObj,worksPath+"/daily_news_java.pdf",new String[]{worksPath+"templates/assets/css/news.css"});} catch (Exception e) {System.err.println("Error generating PDF:");e.printStackTrace();}}
注意:1、如果直接cp上面的代碼,需要在windows 系統的E盤下逐層創建?“E:\HtmlToPdf\templates\assets\css\”目錄,并將上面的css 樣式代碼貼到當前目錄新建的news.css文件。
2、逐層創建“E:\HtmlToPdf\templates\assets\images\”目錄并在其目錄下存入對應圖片文件
3、逐層創建“E:\HtmlToPdf\templates\”目錄并在其目錄下創建名為“newsjava.html”的模板文件并將上面的HTML 內容貼到里面
6、修改PdfGenerator 類頭的package com.powerbridge.pbplatformcarouteserver.utils;引用即可。
7、將上面的main函數直接貼到PdfGenerator中即可運行?
?
?
?
?