SpringBoot+Freemark渲染html導(dǎo)出PDF

SpringBoot+Freemark渲染html導(dǎo)出PDF

摘要

PDF 導(dǎo)出在需要將信息紙質(zhì)化存檔時(shí)會(huì)使用到苹威。這里將介紹在 spring boot 框架下使用 Freemarker + iText 將 ftl 模板渲染成 html,然后導(dǎo)出 PDF 文件

Freemarker 官方文檔: https://freemarker.apache.org/docs/index.html

Maven依賴

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-freemarker</artifactId>
</dependency>
<dependency>
    <groupId>com.itextpdf</groupId>
    <artifactId>html2pdf</artifactId>
    <version>4.0.3</version>
</dependency>

核心代碼

@GetMapping(value = "/export-pdf")
public ResponseEntity exportPDF(TopoDeviceQueryDto queryDto) {
    ResponseEntity response = null;
        try {
        HashMap<String, Object> mapData = Maps.newHashMap();
        mapData.put("topDeviceList", topoDeviceService.findByList(queryDto));
        String templateContent = HtmlUtils.getTemplateContent("TopoDevice.ftl", mapData);
        response = this.getDownloadResponse(HtmlUtils.html2Pdf(templateContent), "device info.pdf");
    } catch (Exception e) {
        log.error("error occurs when downloading file");
        response = ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
    }
    return response;
}

@Slf4j
public class HtmlUtils {

    /**
     * @return
     * @throws Exception
     */
    public static String getTemplateDirectory() {
        ClassLoader classLoader = HtmlUtils.class.getClassLoader();
        URL resource = classLoader.getResource("templates");
        try {
            return Objects.requireNonNull(resource).toURI().getPath();
        } catch (URISyntaxException e) {
            log.error("獲取模板文件夾失敗,{}", e);
        }
        return null;
    }

    /**
     * 獲取模板內(nèi)容
     *
     * @param templateName 模板文件名
     * @param paramMap     模板參數(shù)
     * @return
     * @throws Exception
     */
    public static String getTemplateContent(String templateName, Map<String, Object> paramMap) throws Exception {
        Configuration config = ApplicationContextUtil.getBean(FreeMarkerConfigurer.class).getConfiguration();
        config.setDefaultEncoding("UTF-8");
        Template template = config.getTemplate(templateName, "UTF-8");
        return FreeMarkerTemplateUtils.processTemplateIntoString(template, paramMap);
    }

    /**
     * HTML 轉(zhuǎn) PDF
     *
     * @param content html內(nèi)容
     * @param outPath 輸出pdf路徑
     * @return 是否創(chuàng)建成功
     */
    public static boolean html2Pdf(String content, String outPath) {
        try {
            ConverterProperties converterProperties = new ConverterProperties();
            converterProperties.setCharset("UTF-8");
            FontProvider fontProvider = new FontProvider();
            fontProvider.addSystemFonts();
            converterProperties.setFontProvider(fontProvider);
            HtmlConverter.convertToPdf(content, new FileOutputStream(outPath), converterProperties);
        } catch (Exception e) {
            log.error("生成模板內(nèi)容失敗,{}", e);
            return false;
        }
        return true;
    }

    /**
     * HTML 轉(zhuǎn) PDF
     *
     * @param content html內(nèi)容
     * @return PDF字節(jié)數(shù)組
     */
    public static ByteArrayOutputStream html2Pdf(String content) {
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        try {
            ConverterProperties converterProperties = new ConverterProperties();
            converterProperties.setCharset("UTF-8");
            FontProvider fontProvider = new FontProvider();
            fontProvider.addSystemFonts();
            converterProperties.setFontProvider(fontProvider);
            HtmlConverter.convertToPdf(content, outputStream, converterProperties);
        } catch (Exception e) {
            log.error("生成 PDF 失敗,{}", e);
        }
        return outputStream;
    }
}

@Configuration
@AutoConfigureOrder(-1)
public class ApplicationContextUtil implements ApplicationContextAware {

    private static ApplicationContext applicationContext = null;

    public static Object getBeanByName(String beanName) {
        if (applicationContext == null) {
            return null;
        }
        return applicationContext.getBean(beanName);
    }

    public static <T> T getBean(Class<T> type) {
        return applicationContext.getBean(type);
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        ApplicationContextUtil.applicationContext = applicationContext;
    }


}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UFT-8">
    <title>網(wǎng)絡(luò)拓?fù)浣Y(jié)構(gòu)表</title>
    <style>

        .vertical-line {
            height: 26px;
            border-right: 2px solid #d0d0d0;
            float: left;
            margin-top: -10px;
            margin-left: -15px;
        }

        .horizontal-line {
            width: 15px;
            border-top: 2px solid #d0d0d0;
            float: left;
            margin-top: 16px;
            margin-left: -15px;
        }
    </style>
</head>

<style type="text/css">
    table {
        border-collapse: collapse;
        margin: 0 auto;
        text-align: center;
    }

    .table td,
    .table th {
        border: 1px solid #cad9ea;
        color: #666;
        height: 30px;
    }

    .table thead th {
        background-color: #cce8eb;
        width: 100px;
    }

    .table tr:nth-child(odd) {
        background: #fff;
    }

    .table tr:nth-child(even) {
        background: #f5fafa;
    }

    .tableB th {
        border: 1px solid #cad9ea;
        color: #666;
        height: 30px;
    }

    .tableB thead th {
        background-color: #e7f1ef;
        width: 100px;
    }
</style>

<!-- Table goes in the document BODY -->

<body>
<div>
    <table width="90%" class="table">
        <caption>
            <h2>網(wǎng)絡(luò)拓?fù)浣Y(jié)構(gòu)表</h2>
        </caption>
        <thead>
        <tr>
            <th>設(shè)備名稱</th>
            <th>符號(hào)</th>
            <th>端口</th>
            <th>地址</th>
            <th>網(wǎng)絡(luò)中的單元</th>
        </tr>
        </thead>
        <tbody>

        <#if topDeviceList??>
            <#list topDeviceList as top_device>
                <tr>
                    <td><#if top_device.deviceName??>${top_device.deviceName}</#if></td>
                    <td><#if top_device.mark??>${top_device.mark}</#if></td>
                    <td><#if top_device.port??>${top_device.port}</#if></td>
                    <td><#if top_device.ip??>${top_device.ip}</#if></td>
                    <td><#if top_device.unit??>${top_device.unit}</#if></td>
                </tr>
            </#list>
        </#if>

        </tbody>
    </table>
</div>
</body>
</html>

image-20230324111612922.png

踩坑記錄

解決Spring項(xiàng)目打成Jar包后Freemarker找不到模板的問題

freemarker在jar包中無法使用類加載器獲取resourse目錄下的templates文件咖摹,出現(xiàn)的問題代碼如下:(本地測(cè)試正常絮宁,打包jar后無法獲取模板)

    @GetMapping(value = "/export-pdf")
    public ResponseEntity exportPDF(TopoDeviceQueryDto queryDto) {
        ResponseEntity response = null;
        try {
            HashMap<String, Object> mapData = Maps.newHashMap();
            mapData.put("topDeviceList", topoDeviceService.findByList(queryDto));
            String templateContent = HtmlUtils.getTemplateContent("TopoDevice.ftl", mapData);
            response = this.getDownloadResponse(HtmlUtils.html2Pdf(templateContent), "device info.pdf");
        } catch (Exception e) {
            log.error("error occurs when downloading file");
            response = ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
        }
        return response;
    }


    public static String getTemplateDirectory() {
        ClassLoader classLoader = HtmlUtils.class.getClassLoader();
        URL resource = classLoader.getResource("templates");
        try {
            return Objects.requireNonNull(resource).toURI().getPath();
        } catch (URISyntaxException e) {
            log.error("獲取模板文件夾失敗,{}", e);
        }
        return null;
    }

    /**
     * 獲取模板內(nèi)容
     *
     * @param templateDirectory 模板文件夾
     * @param templateName      模板文件名
     * @param paramMap          模板參數(shù)
     * @return
     * @throws Exception
     */
    public static String getTemplateContent(String templateDirectory, String templateName, Map<String, Object> paramMap) throws Exception {
        Configuration configuration = new Configuration(Configuration.DEFAULT_INCOMPATIBLE_IMPROVEMENTS);
        try {
            configuration.setDirectoryForTemplateLoading(new File(templateDirectory));
        } catch (Exception e) {
            System.out.println("-- exception --");
        }

        Writer out = new StringWriter();
        Template template = configuration.getTemplate(templateName, "UTF-8");
        template.process(paramMap, out);
        out.flush();
        out.close();
        return out.toString();
    }

    /**
     * HTML 轉(zhuǎn) PDF
     *
     * @param content html內(nèi)容
     * @return PDF字節(jié)數(shù)組
     */
    public static ByteArrayOutputStream html2Pdf(String content) {
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        try {
            ConverterProperties converterProperties = new ConverterProperties();
            converterProperties.setCharset("UTF-8");
            FontProvider fontProvider = new FontProvider();
            fontProvider.addSystemFonts();
            converterProperties.setFontProvider(fontProvider);
            HtmlConverter.convertToPdf(content, outputStream, converterProperties);
        } catch (Exception e) {
            log.error("生成 PDF 失敗,{}", e);
        }
        return outputStream;
    }

修改后的代碼(打包jar后正常獲取模板信息)

    @GetMapping(value = "/export-pdf")
    public ResponseEntity exportPDF(TopoDeviceQueryDto queryDto) {
        ResponseEntity response = null;
        try {
            HashMap<String, Object> mapData = Maps.newHashMap();
            mapData.put("topDeviceList", topoDeviceService.findByList(queryDto));
            String templateContent = HtmlUtils.getTemplateContent("TopoDevice.ftl", mapData);
            response = this.getDownloadResponse(HtmlUtils.html2Pdf(templateContent), "device info.pdf");
        } catch (Exception e) {
            log.error("error occurs when downloading file");
            response = ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
        }
        return response;
    }

    /**
     * 獲取模板內(nèi)容
     *
     * @param templateName 模板文件名
     * @param paramMap     模板參數(shù)
     * @return
     * @throws Exception
     */
    public static String getTemplateContent(String templateName, Map<String, Object> paramMap) throws Exception {
        Configuration config = ApplicationContextUtil.getBean(FreeMarkerConfigurer.class).getConfiguration();
        config.setDefaultEncoding("UTF-8");
        Template template = config.getTemplate(templateName, "UTF-8");
        return FreeMarkerTemplateUtils.processTemplateIntoString(template, paramMap);
    }

    public static <T> T getBean(Class<T> type) {
        return applicationContext.getBean(type);
    }

    /**
     * HTML 轉(zhuǎn) PDF
     *
     * @param content html內(nèi)容
     * @return PDF字節(jié)數(shù)組
     */
    public static ByteArrayOutputStream html2Pdf(String content) {
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        try {
            ConverterProperties converterProperties = new ConverterProperties();
            converterProperties.setCharset("UTF-8");
            FontProvider fontProvider = new FontProvider();
            fontProvider.addSystemFonts();
            converterProperties.setFontProvider(fontProvider);
            HtmlConverter.convertToPdf(content, outputStream, converterProperties);
        } catch (Exception e) {
            log.error("生成 PDF 失敗,{}", e);
        }
        return outputStream;
    }

ps:.ftl模板文件放在 templates 目錄下

總結(jié):freemarker無法使用類加載器獲取jar包中的resourse目錄下的templates文件
解決辦法:注入FreeMarkerConfigurer配置類钙皮,因?yàn)閒reemarker模板的默認(rèn)目錄就在resourse下的templates目錄下符欠,
使用freeMarkerConfigurer.getConfiguration().getTemplate("mailTemplate.ftl")可直接獲取到對(duì)應(yīng)的模板文件

解決Freemark導(dǎo)出Pdf部署Linux亂碼問題

項(xiàng)目部署完之后發(fā)現(xiàn)Linux下個(gè)別字體丟失的問題调限,剛開始以為是編碼問題麻捻,經(jīng)排查是Linux系統(tǒng)中文字體缺失問題

第一步:拷貝Windows下系統(tǒng)的中文字體 Windows下字體的目錄是在C:\Windows\Fonts

第二步:移動(dòng)字體庫到linux系統(tǒng)下的字體庫文件夾/usr/share/fonts/下

第三步:讓linux系統(tǒng)識(shí)別新的中文字體:終端輸入:sudo fc-cache -fv

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個(gè)濱河市兼蕊,隨后出現(xiàn)的幾起案子初厚,更是在濱河造成了極大的恐慌,老刑警劉巖孙技,帶你破解...
    沈念sama閱讀 221,695評(píng)論 6 515
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件产禾,死亡現(xiàn)場(chǎng)離奇詭異,居然都是意外死亡牵啦,警方通過查閱死者的電腦和手機(jī)亚情,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 94,569評(píng)論 3 399
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來哈雏,“玉大人楞件,你說我怎么就攤上這事∩驯瘢” “怎么了土浸?”我有些...
    開封第一講書人閱讀 168,130評(píng)論 0 360
  • 文/不壞的土叔 我叫張陵,是天一觀的道長彭羹。 經(jīng)常有香客問我黄伊,道長,這世上最難降的妖魔是什么派殷? 我笑而不...
    開封第一講書人閱讀 59,648評(píng)論 1 297
  • 正文 為了忘掉前任还最,我火速辦了婚禮墓阀,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘拓轻。我一直安慰自己斯撮,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 68,655評(píng)論 6 397
  • 文/花漫 我一把揭開白布悦即。 她就那樣靜靜地躺著吮成,像睡著了一般。 火紅的嫁衣襯著肌膚如雪辜梳。 梳的紋絲不亂的頭發(fā)上粱甫,一...
    開封第一講書人閱讀 52,268評(píng)論 1 309
  • 那天,我揣著相機(jī)與錄音作瞄,去河邊找鬼茶宵。 笑死,一個(gè)胖子當(dāng)著我的面吹牛宗挥,可吹牛的內(nèi)容都是我干的乌庶。 我是一名探鬼主播,決...
    沈念sama閱讀 40,835評(píng)論 3 421
  • 文/蒼蘭香墨 我猛地睜開眼契耿,長吁一口氣:“原來是場(chǎng)噩夢(mèng)啊……” “哼瞒大!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起搪桂,我...
    開封第一講書人閱讀 39,740評(píng)論 0 276
  • 序言:老撾萬榮一對(duì)情侶失蹤透敌,失蹤者是張志新(化名)和其女友劉穎,沒想到半個(gè)月后踢械,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體酗电,經(jīng)...
    沈念sama閱讀 46,286評(píng)論 1 318
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 38,375評(píng)論 3 340
  • 正文 我和宋清朗相戀三年内列,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了撵术。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 40,505評(píng)論 1 352
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡话瞧,死狀恐怖嫩与,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情移稳,我是刑警寧澤蕴纳,帶...
    沈念sama閱讀 36,185評(píng)論 5 350
  • 正文 年R本政府宣布,位于F島的核電站个粱,受9級(jí)特大地震影響,放射性物質(zhì)發(fā)生泄漏翻翩。R本人自食惡果不足惜都许,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,873評(píng)論 3 333
  • 文/蒙蒙 一稻薇、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧胶征,春花似錦塞椎、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,357評(píng)論 0 24
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至钱雷,卻和暖如春骂铁,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背罩抗。 一陣腳步聲響...
    開封第一講書人閱讀 33,466評(píng)論 1 272
  • 我被黑心中介騙來泰國打工拉庵, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留,地道東北人套蒂。 一個(gè)月前我還...
    沈念sama閱讀 48,921評(píng)論 3 376
  • 正文 我出身青樓钞支,卻偏偏與公主長得像,于是被迫代替她去往敵國和親操刀。 傳聞我的和親對(duì)象是個(gè)殘疾皇子烁挟,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 45,515評(píng)論 2 359

推薦閱讀更多精彩內(nèi)容