摘要:格式文檔導(dǎo)出,是信息系統(tǒng)中非常實(shí)用的一種功能,用于各種報(bào)表和文檔的到處。示例中,使用生成要導(dǎo)出的格式文檔,通過來實(shí)現(xiàn)文件下載。將轉(zhuǎn)換成文檔生成的代碼比較簡(jiǎn)單,創(chuàng)建一個(gè)對(duì)象,然后會(huì)在指定的中輸入生成的文件。作用相當(dāng)于在中使用進(jìn)行配置。
PDF格式文檔導(dǎo)出,是信息系統(tǒng)中非常實(shí)用的一種功能,用于各種報(bào)表和文檔的到處。最近正好有空,用之前項(xiàng)目中使用過的itext做一個(gè)簡(jiǎn)單的示例,方便以后使用。示例中,使用Freemarker生成要導(dǎo)出的HTML格式文檔,通過Spring Boot來實(shí)現(xiàn)PDF文件下載。
創(chuàng)建Gradle項(xiàng)目源代碼:GitHub
需要在build.gradle中添加要引入的jar包,還有Gradle插件。主要有spring boot plugin和spring boot相關(guān)的包;freemarker,還有itextpdf,這里的itext-asian會(huì)引入中文支持。
buildscript { repositories { mavenLocal() mavenCentral() } dependencies { classpath("org.freemarker:freemarker:2.3.23") classpath("org.springframework.boot:spring-boot-gradle-plugin:1.4.0.RELEASE") } } ... ... dependencies { // tag::jetty[] compile("org.springframework.boot:spring-boot-starter-web") { exclude module: "spring-boot-starter-tomcat" } compile("org.springframework.boot:spring-boot-starter-jetty") // end::jetty[] // tag::actuator[] compile("org.springframework.boot:spring-boot-starter-actuator") compile("org.springframework.boot:spring-boot-starter-aop") compile("org.springframework:spring-context-support") compile "com.itextpdf:itextpdf:5.5.9" compile "com.itextpdf:itext-asian:5.2.0" compile "com.itextpdf.tool:xmlworker:5.5.9" compile "org.freemarker:freemarker:2.3.23" compile "javax.servlet:javax.servlet-api:3.1.0" testCompile (group: "junit", name: "junit", version: "4.12") testCompile("org.springframework.boot:spring-boot-starter-test") }用Freemarker來生成html字符串
freemarker是一種非常輕量易用的模板引擎,除了用于在web mvc框架中渲染html頁面以外,還可以用在其他需要生成其他有復(fù)雜格式的文檔,并且需要用數(shù)據(jù)進(jìn)行格式化的場(chǎng)景下;將生成的字符串寫入指定的Java流中。
public class FreemarkerUtils { public static String loadFtlHtml(File baseDir, String fileName,Map globalMap){ if(baseDir == null || !baseDir.isDirectory() || globalMap ==null || fileName == null || "".equals(fileName)){ throw new IllegalArgumentException("Directory file"); } Configuration cfg = new Configuration(Configuration.VERSION_2_3_22); try { cfg.setDirectoryForTemplateLoading(baseDir); cfg.setDefaultEncoding("UTF-8"); cfg.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER);//.RETHROW cfg.setClassicCompatible(true); Template temp = cfg.getTemplate(fileName); StringWriter stringWriter = new StringWriter(); temp.process(globalMap, stringWriter); return stringWriter.toString(); } catch (IOException | TemplateException e) { e.printStackTrace(); throw new RuntimeException("load fail file"); } } }
傳入的參數(shù)是ftl文件的根目錄和文件名,還有要用來格式化文檔的數(shù)據(jù)。
itext將html轉(zhuǎn)換成PDF文檔itext生成PDF的代碼比較簡(jiǎn)單,創(chuàng)建一個(gè)Document對(duì)象,然后XmlWorkerHelper會(huì)在指定的OutputStream中輸入生成的pdf文件。
public static void savePdf(OutputStream out, String html) { Document document = new Document(PageSize.A4, 50, 50, 60, 60); try { PdfWriter writer = PdfWriter.getInstance(document, out); document.open(); XMLWorkerHelper.getInstance().parseXHtml(writer, document, new StringReader(html)); } catch (Exception e) { e.printStackTrace(); } finally { document.close(); } }
如果簡(jiǎn)單的實(shí)現(xiàn)文件下載的話,可以直接使用HttpServletResponse的OutputStream,就可以實(shí)現(xiàn)pdf下載,但是Spring MVC支持自定義View,使用Spring boot可以通過簡(jiǎn)單的配置實(shí)現(xiàn)對(duì)應(yīng)功能。
集成Spring Boot實(shí)現(xiàn)文件下載Spring MVC通過繼承基類AbstractView,可以實(shí)現(xiàn)自定義的View,在子類中,可以設(shè)置header,通過對(duì)輸出流的操作,就可以實(shí)現(xiàn)在Java代碼中調(diào)用需要的資源,輸出對(duì)應(yīng)的內(nèi)容的功能。詳細(xì)內(nèi)容參看源代碼。
@Override protected void renderMergedOutputModel(Mapmodel, HttpServletRequest request, HttpServletResponse response) throws Exception { // IE workaround: write into byte array first. ByteArrayOutputStream baos = createTemporaryOutputStream(); // Apply preferences and build metadata. Document document = newDocument(); PdfWriter writer = newWriter(document, baos); prepareWriter(model, writer, request); buildPdfMetadata(model, document, request); // Build PDF document. document.open(); buildPdfDocument(model, document, writer, request, response); document.close(); // Flush to HTTP response. writeToResponse(response, baos); } ...... protected void buildPdfDocument(Map model, Document document, PdfWriter writer, HttpServletRequest request, HttpServletResponse response) throws Exception { URL fileResource = FormPdfview.class.getResource("/templates"); String html = FreemarkerUtils.loadFtlHtml(new File(fileResource.getFile()), "simpleForm.ftl", model); XMLWorkerHelper.getInstance().parseXHtml(writer, document, new ByteArrayInputStream(html.getBytes()), Charset.forName("UTF-8"), new AsianFontProvider() ); }
為了能夠在Spring MVC的控制器中通過MVC模式調(diào)用自定義的View對(duì)象,還需要進(jìn)行一些配置;
首先,在WebMvcConfigurerAdapter的子類中,添加view resolver配置。作用相當(dāng)于在spring mvc中使用xml進(jìn)行配置。
@Bean public ResourceBundleViewResolver viewResolver() { ResourceBundleViewResolver resolver = new ResourceBundleViewResolver(); resolver.setOrder(1); resolver.setBasename("views"); return resolver; }
然后要在resources目錄下創(chuàng)建一個(gè)views.properties文件,為我們自定義的view指定一個(gè)名字,就可以在controller中正常使用。
simplePDF.(class)=com.liuwill.text.view.Pdfview simpleFormPDF.(class)=com.liuwill.text.view.FormPdfview效果
下載源代碼之后,執(zhí)行gradle bootRun來運(yùn)行Spring Boot,運(yùn)行起來之后,訪問 http://localhost:8888/download 查看結(jié)果。
文/liuwill(簡(jiǎn)書作者)
原文鏈接:Spring Boot集成Freemarker和iText生成PDF文檔
著作權(quán)歸作者所有,轉(zhuǎn)載請(qǐng)聯(lián)系作者獲得授權(quán),并標(biāo)注“簡(jiǎn)書作者”。
文章版權(quán)歸作者所有,未經(jīng)允許請(qǐng)勿轉(zhuǎn)載,若此文章存在違規(guī)行為,您可以聯(lián)系管理員刪除。
轉(zhuǎn)載請(qǐng)注明本文地址:http://www.ezyhdfw.cn/yun/66755.html
摘要:由于工作需要,要實(shí)現(xiàn)后端根據(jù)模板動(dòng)態(tài)填充數(shù)據(jù)生成文檔,通過技術(shù)選型,使用來設(shè)計(jì)模板,結(jié)合工具庫來調(diào)用渲染生成文檔。 由于工作需要,要實(shí)現(xiàn)后端根據(jù)模板動(dòng)態(tài)填充數(shù)據(jù)生成PDF文檔,通過技術(shù)選型,使用Ireport5.6來設(shè)計(jì)模板,結(jié)合JasperReports5.6工具庫來調(diào)用渲染生成PDF文檔。本人文采欠缺,寫作能力差,下面粗略的介紹其使用步驟,若有不對(duì)的地方,望大家莫噴,謝謝! 一、使...
摘要:一需求說明根據(jù)業(yè)務(wù)需要,需要在服務(wù)器端生成可動(dòng)態(tài)配置的文檔,方便數(shù)據(jù)可視化查看。能配置動(dòng)態(tài)的模板,正好解決了樣式動(dòng)態(tài)渲染和排版問題。包負(fù)責(zé)模板之外的額外信息填寫,這里主要是頁眉頁腳的定制。包的畫圖工具包,目前只有一個(gè)線形圖。 一、需求說明:根據(jù)業(yè)務(wù)需要,需要在服務(wù)器端生成可動(dòng)態(tài)配置的PDF文檔,方便數(shù)據(jù)可視化查看。 二、解決方案:iText+FreeMarker+JFreeChart生...
摘要:一需求說明根據(jù)業(yè)務(wù)需要,需要在服務(wù)器端生成可動(dòng)態(tài)配置的文檔,方便數(shù)據(jù)可視化查看。能配置動(dòng)態(tài)的模板,正好解決了樣式動(dòng)態(tài)渲染和排版問題。包負(fù)責(zé)模板之外的額外信息填寫,這里主要是頁眉頁腳的定制。包的畫圖工具包,目前只有一個(gè)線形圖。 一、需求說明:根據(jù)業(yè)務(wù)需要,需要在服務(wù)器端生成可動(dòng)態(tài)配置的PDF文檔,方便數(shù)據(jù)可視化查看。 二、解決方案:iText+FreeMarker+JFreeChart生...
摘要:日期和時(shí)間處理日期和時(shí)間的函數(shù)庫。使用中可觀察序列,創(chuàng)建異步基于事件應(yīng)用程序的函數(shù)庫。為分布式系統(tǒng)提供延遲和容錯(cuò)處理。發(fā)布使用本機(jī)格式分發(fā)應(yīng)用程序的工具。將程序資源和打包成和的本機(jī)文件。圖像處理用來幫助創(chuàng)建評(píng)估或操作圖形的函數(shù)庫。 好資源要分享原文 譯者 唐尤華 翻譯自 github akullpp 構(gòu)建 這里搜集了用來構(gòu)建應(yīng)用程序的工具。 Apache Maven:Mave...
摘要:數(shù)據(jù)和信息是不可分離的,數(shù)據(jù)是信息的表達(dá),信息是數(shù)據(jù)的內(nèi)涵。數(shù)據(jù)本身沒有意義,數(shù)據(jù)只有對(duì)實(shí)體行為產(chǎn)生影響時(shí)才成為信息。主要目標(biāo)是為開發(fā)提供天然的模板,并且能在里面準(zhǔn)確的顯示。目前是自然更加推薦。 這是泥瓦匠的第105篇原創(chuàng) 文章工程: JDK 1.8 Maven 3.5.2 Spring Boot 2.1.3.RELEASE 工程名:springboot-webflux-4-thym...
閱讀 1349·2021-11-23 09:51
閱讀 1688·2021-11-16 11:45
閱讀 4466·2021-10-09 09:43
閱讀 2824·2021-07-22 16:47
閱讀 1011·2019-08-27 10:55
閱讀 3523·2019-08-26 17:40
閱讀 3170·2019-08-26 11:39
閱讀 3313·2019-08-23 18:39