日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁 > 前端技术 > javascript >内容正文

javascript

Spring Boot——Thymeleaf生成PDF实战教程

發(fā)布時(shí)間:2023/12/20 javascript 32 豆豆
生活随笔 收集整理的這篇文章主要介紹了 Spring Boot——Thymeleaf生成PDF实战教程 小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.

目錄

  • 前言
  • 一、引入依賴
    • 1.Thymeleaf,生成PDF相關(guān)依賴
  • 二、application.yml配置
    • 1.yml配置文件
  • 三、PDF相關(guān)配置
    • 1.PDF配置代碼(如下):
  • 四、Controller
    • 1.請求接口報(bào)錯(cuò)解決方式:
  • 五、生成PDF文件響應(yīng)效果


前言

溫馨提示:本博客使用Thymeleaf模板引擎實(shí)現(xiàn)PDF打印僅供參考:

在閱讀該博客之前,先要了解一下Thymeleaf模板引擎,因?yàn)槭鞘褂肨hymeleaf模板引擎實(shí)現(xiàn)的PDF打印的,

Thymeleaf是一個(gè)現(xiàn)代的服務(wù)器端 Java 模板引擎,適用于 Web 和獨(dú)立環(huán)境。

Thymeleaf 的主要目標(biāo)是為您的開發(fā)工作流程帶來優(yōu)雅的自然模板——HTML可以在瀏覽器中正確顯示,也可以用作靜態(tài)原型,從而在開發(fā)團(tuán)隊(duì)中實(shí)現(xiàn)更強(qiáng)大的協(xié)作。

借助 Spring Framework 的模塊、與您最喜歡的工具的大量集成以及插入您自己的功能的能力,Thymeleaf 是現(xiàn)代 HTML5 JVM Web 開發(fā)的理想選擇——盡管它可以做的更多。
不了解小伙伴可以去Thymeleaf官網(wǎng)查看,有更詳細(xì)的講解。
接下來就不一一介紹了,直接上代碼。


一、引入依賴

1.Thymeleaf,生成PDF相關(guān)依賴

1.1,以下依賴為必要依賴,一個(gè)都不能少,依賴version可以根基實(shí)際情況使用相關(guān)的依賴版本。

二、application.yml配置

1.yml配置文件

yml配置文件使用配置thymeleaf模板路徑(示例):

以上相關(guān)為基礎(chǔ)且必須配置的內(nèi)容,接下來繼續(xù)講解thymeleaf引擎需要生成PDF的相關(guān)配置。


三、PDF相關(guān)配置

1.PDF配置代碼(如下):

package com.cy.xgsm.configuration;import java.io.IOException; import java.io.InputStream; import java.net.URISyntaxException;import org.apache.commons.io.IOUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration;import com.itextpdf.html2pdf.ConverterProperties; import com.itextpdf.html2pdf.resolver.font.DefaultFontProvider; import com.itextpdf.io.font.PdfEncodings; import com.itextpdf.kernel.font.PdfFont; import com.itextpdf.kernel.font.PdfFontFactory; import com.itextpdf.layout.font.FontProvider; import com.cy.xgsm.controller.PrintPdfController;/*** * @author Dylan* PDF相關(guān)配置*/ @Configuration public class PdfConfiguration {private static final Logger log = LoggerFactory.getLogger(PdfConfiguration.class);@Beanpublic FontProvider getFontProvider() throws URISyntaxException, IOException {FontProvider provider = new DefaultFontProvider(true, true, false);byte[] bs = null;//SIMSUN.TTC為字體try (InputStream in = PrintPdfController.class.getClassLoader().getResourceAsStream("font/SIMSUN.TTC")) {bs = IOUtils.toByteArray(in);} PdfFont pdfFont = PdfFontFactory.createTtcFont(bs, 1, PdfEncodings.IDENTITY_H, false, true);provider.addFont(pdfFont.getFontProgram());return provider;}@Beanpublic ConverterProperties converterProperties(FontProvider fontProvider, Configuration config) {ConverterProperties cp = new ConverterProperties();cp.setBaseUri(config.getPdfUrl());try {cp.setFontProvider(fontProvider);} catch (Exception e) {log.error("打印PDF時(shí)未能添加字體", e);}return cp;}}

一,注意PDF配置需要添加打印PDF字體,SIMSUN.TTC為打印需要的字體,但是也可以是其他的

四、Controller

1.以上所有的相關(guān)配置信息都配置完了,接下來就可以寫Api接口了

package com.cy.xgsm.controller;import java.io.IOException; import java.io.OutputStream; import java.net.URLEncoder;import javax.servlet.http.HttpServletResponse;import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.thymeleaf.TemplateEngine; import org.thymeleaf.context.Context;import com.itextpdf.html2pdf.ConverterProperties; import com.itextpdf.html2pdf.HtmlConverter; import com.itextpdf.kernel.geom.PageSize; import com.itextpdf.kernel.pdf.PdfDocument; import com.itextpdf.kernel.pdf.PdfWriter; import com.cy.xgsm.common.Result; import com.cy.xgsm.model.OrderInfo; import com.cy.xgsm.service.OrderInfoService;/*** 打印PDF 控制接入層* * @author Dylan**/ @Controller @RequestMapping("print") public class PrintPdfController {private static final Logger log = LoggerFactory.getLogger(PrintPdfController.class);@Autowiredprivate OrderInfoService service;//thymeleaf模板引擎@AutowiredTemplateEngine templateEngine;//html轉(zhuǎn)換成pdf需要使用ConverterProperties@AutowiredConverterProperties converterProperties; @GetMapping("order/{orderId}.pdf")public void orderPdf(@PathVariable Long orderId, HttpServletResponse resp) throws IOException {Result<OrderInfo> result = service.selectByPrimaryKey(orderId);if (!result.isComplete()) {resp.sendError(404, "訂單ID不存在");}Context context = new Context();context.setVariable("order", result.getData());///html/pdf/order-template為打印模板紙張路徑processPdf(context, "/html/pdf/order-template", result.getData().getKddh(), resp);}/*** 調(diào)用生成PDF* @param context 上下文* @param template 模板文件* @param filename 文件名* @param resp*/private void processPdf(Context context, String template, String filename, HttpServletResponse resp) throws IOException {log.info("生成PDF:" + filename);String html = templateEngine.process(template, context);String filenameEncoded = URLEncoder.encode(filename, "utf-8");resp.setContentType("application/pdf");resp.setHeader("Content-Disposition", "filename=" + filenameEncoded + ".pdf");try (OutputStream out = resp.getOutputStream()) {PdfDocument doc = new PdfDocument(new PdfWriter(out));//打印使用什么什么紙張可根據(jù)實(shí)際情況,我這里默認(rèn)使用A4doc.setDefaultPageSize(PageSize.A4.rotate());HtmlConverter.convertToPdf(html, doc, converterProperties);}}}

1.請求接口報(bào)錯(cuò)解決方式:

如果在請求接口的時(shí)候發(fā)生以下錯(cuò)誤信息是打印模板的路徑錯(cuò)誤了。

解決該錯(cuò)誤需在你的yml配置thymeleaf路徑即可,不懂怎么配置請往上看第二點(diǎn)application.yml配置,可按照application.yml復(fù)制上去即可解決。

五、生成PDF文件響應(yīng)效果


點(diǎn)擊Save to a file保存,響應(yīng)結(jié)果數(shù)據(jù)均為測試數(shù)據(jù),僅供參考。

總結(jié)

以上是生活随笔為你收集整理的Spring Boot——Thymeleaf生成PDF实战教程的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。