java按照模板導(dǎo)出pdf或word文件詳細(xì)代碼
一、java按照模板導(dǎo)出pdf
(一)制作模板
1、在word里制作模板
因?yàn)镻DF常用的軟件不支持編輯,所以先用Word工具,如WPS或者Office新建一個(gè)空白Word文檔,里面制作出自己想要的樣式。
2、 將Word轉(zhuǎn)換成PDF形式
將設(shè)置好的Word文檔轉(zhuǎn)換成PDF形式,保存起來(lái)。
3、編輯PDF準(zhǔn)備表單
用Adobe Acrobat DC 軟件打開(kāi)保存好的PDF模板文件,點(diǎn)擊右側(cè)的準(zhǔn)備表單按鈕
接下來(lái)進(jìn)行數(shù)據(jù)源配置,在要顯示圖像的區(qū)域,點(diǎn)擊鼠標(biāo)右鍵,選擇文本域,設(shè)定好圖像的顯示位置,并指定數(shù)據(jù)源字段。需要注意的是,配置的數(shù)據(jù)源字段必須與Java中的實(shí)體類對(duì)象的字段名保持一致。
配置完成之后保存pdf文件,留作模板使用。
(二)java代碼編寫(xiě)
1、導(dǎo)入依賴
<dependency> <groupId>com.itextpdf</groupId> <artifactId>itextpdf</artifactId> <version>5.5.13</version> </dependency> <dependency> <groupId>com.itextpdf</groupId> <artifactId>itext-asian</artifactId> <version>5.2.0</version> </dependency>
2、實(shí)體類
import lombok.Data; /** * 報(bào)表實(shí)體類 */ @Data public class MsaBusinessVO { /**接收業(yè)務(wù)總次數(shù)*/ private String total; /**接收業(yè)務(wù)總次數(shù)(去年同期)*/ private String lastToatl; /**處理次數(shù)*/ private String dealNum; /**處理次數(shù)(去年同期)*/ private String lastDealNum; /**已完成次數(shù)*/ private String completeNum; /**已完成次數(shù)(去年同期)*/ private String lastCompleteNum; /**售后次數(shù)*/ private String afterSales; /**售后次數(shù)(去年同期)*/ private String lastAfterSales; }
3、service層代碼實(shí)現(xiàn)
/** * 生成報(bào)表 * @param id * @param response */ void generateMsaBusiness(String id,HttpServletResponse response) throws UnsupportedEncodingException;
@Override public void generateMsaBusiness(String id,HttpServletResponse response) throws UnsupportedEncodingException { //通過(guò)id獲取msaBusinessVO MsaBusinessVO msaBusinessVO = msaBusinessDao.getMsaBusinessInfo(id); // 模板名稱 String templateName = "msaBusiness.pdf"; String path = "/static/template/"; //String path = ""; // 獲取操作系統(tǒng)名稱,根據(jù)系統(tǒng)名稱確定模板存放的路徑 /*String systemName = System.getProperty("os.name"); if(systemName.toUpperCase().startsWith("WIN")){ path = "D:/pdf/"; }else { path = "/usr/local/pdf/"; }*/ // 生成導(dǎo)出PDF的文件名稱 String fileName = "海事行政執(zhí)法業(yè)務(wù)數(shù)據(jù)統(tǒng)計(jì)"+msaBusinessVO.getStartDate()+"至"+msaBusinessVO.getEndDate()+".pdf"; fileName = URLEncoder.encode(fileName, "UTF-8"); // 設(shè)置響應(yīng)頭 response.setContentType("application/force-download"); response.setHeader("Content-Disposition", "attachment;fileName=" + fileName); OutputStream out = null; ByteArrayOutputStream bos = null; PdfStamper stamper = null; PdfReader reader = null; try { // 保存到本地 // out = new FileOutputStream(fileName); // 輸出到瀏覽器端 out = response.getOutputStream(); // 讀取PDF模板表單 reader = new PdfReader(path + templateName); // 字節(jié)數(shù)組流,用來(lái)緩存文件流 bos = new ByteArrayOutputStream(); // 根據(jù)模板表單生成一個(gè)新的PDF stamper = new PdfStamper(reader, bos); // 獲取新生成的PDF表單 AcroFields form = stamper.getAcroFields(); // 給表單生成中文字體,這里采用系統(tǒng)字體,不設(shè)置的話,中文顯示會(huì)有問(wèn)題 //BaseFont font = BaseFont.createFont("C:/WINDOWS/Fonts/SIMSUN.TTC,1", BaseFont.IDENTITY_H, BaseFont.EMBEDDED); BaseFont bf = BaseFont.createFont("/static/fonts/simsun.ttc,1", BaseFont.IDENTITY_H, BaseFont.EMBEDDED); form.addSubstitutionFont(bf); // 裝配數(shù)據(jù) this.setMsaBusinessToForm(form, msaBusinessVO); // 表明該P(yáng)DF不可修改 stamper.setFormFlattening(true); // 關(guān)閉資源 stamper.close(); // 將ByteArray字節(jié)數(shù)組中的流輸出到out中(即輸出到瀏覽器) Document doc = new Document(); PdfCopy copy = new PdfCopy(doc, out); doc.open(); //改成這樣就不會(huì)只顯示一頁(yè)了。 PdfImportedPage importPage = null; ///循環(huán)是處理成品只顯示一頁(yè)的問(wèn)題 for (int i=1;i<=reader.getNumberOfPages();i++){ importPage = copy.getImportedPage(new PdfReader(bos.toByteArray()), i); copy.addPage(importPage); } doc.close(); log.info("*****************************PDF導(dǎo)出成功*********************************"); } catch (Exception e) { e.printStackTrace(); } finally { try { if (out != null) { out.flush(); out.close(); } if (reader != null) { reader.close(); } } catch (Exception e) { e.printStackTrace(); } } } /** * 裝配數(shù)據(jù) * @param form * @param msaBusinessVO * @throws DocumentException * @throws IOException */ public void setMsaBusinessToForm(AcroFields form,MsaBusinessVO msaBusinessVO) throws DocumentException, IOException { form.setField("total",msaBusinessVO.getTotal());//進(jìn)出港船舶總艘次 form.setField("lastTotal",msaBusinessVO.getLastTotal());//進(jìn)出港船舶總艘次(去年同期) form.setField("dealNum",msaBusinessVO.getDealNum());//進(jìn)出港報(bào)告內(nèi)河船艘次 form.setField("lastDealNum",msaBusinessVO.getLastDealNum());//進(jìn)出港報(bào)告內(nèi)河船艘次(去年同期) form.setField("completeNum",msaBusinessVO.getCompleteNum());//進(jìn)出港報(bào)告海船艘次 form.setField("lastCompleteNum",msaBusinessVO.getLastCompleteNum());//進(jìn)出港報(bào)告海船艘次(去年同期) form.setField("afterSales",msaBusinessVO.getAfterSales());//進(jìn)出口岸查驗(yàn)船舶艘次 form.setField("lastAfterSales",msaBusinessVO.getLastAfterSales());//進(jìn)出口岸查驗(yàn)船舶艘次(去年同期) }
4、Controller層代碼實(shí)現(xiàn)
/** * 導(dǎo)出pdf * @param id * @param response */ @GetMapping("/generateMsaBusiness") public void generateMsaBusiness(String id,HttpServletResponse response){ try { msaBusinessService.generateMsaBusiness(id,response); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } }
二、java按照模板導(dǎo)出word
(一)制作模板
1、word模板文件處理,如下圖所示在word 文檔中填值的地方寫(xiě)入占位變量,值得注意的是,word中的占位變量要與java代碼中寫(xiě)入的元素名稱保持一致。
2、將word文檔另存為xml文件,編輯如下圖,找到填寫(xiě)的占位,修改為${total}格式
3、將文件后綴名改為.ftl文件 ,留作模板使用。
(二)java代碼編寫(xiě)
1、引入依賴
<dependency> <groupId>org.freemarker</groupId> <artifactId>freemarker</artifactId> <version>2.3.28</version> <scope>compile</scope> </dependency>
2、service層代碼實(shí)現(xiàn)
/** * 導(dǎo)出word * @param param */ void exportSimpleWord(Map<String,Object> param);
/** * 保存打印記錄 * @param param * Map<String,Object> param 中的字段要與模板中的占位符名稱一致 */ @Override @Transactional(rollbackFor = Exception.class) public void exportSimpleWord(Map<String,Object> param){ //param.put("total",total); //param.put("lastTotal",lastTotal); try { // 要填充的數(shù)據(jù) dataMap, 注意map的key要和word中${xxx}的xxx一致 //Configuration用于讀取ftl文件 Configuration configuration = new freemarker.template.Configuration(Configuration.VERSION_2_3_23); System.out.println(configuration.getVersion()); configuration.setDefaultEncoding("utf-8"); //指定路徑的第一種方式(根據(jù)某個(gè)類的相對(duì)路徑指定) configuration.setClassForTemplateLoading(this.getClass(), "/static/template/"); // 輸出文檔路徑及名稱 File outFile = new File("D:/附件"+new SimpleDateFormat("yyyyMMddHHmmss").format(new Date())+".doc"); //以u(píng)tf-8的編碼讀取ftl文件 名字要正確,最好不要放在本地,可能會(huì)出現(xiàn)找不到。 Template t1 = configuration.getTemplate("unpackCheck.ftl", "utf-8"); // Template t = configuration.getTemplate("a.ftl","utf-8"); Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outFile), "utf-8"), 10240); t1.process(param, out); out.close(); }catch (IOException e) { e.printStackTrace(); } catch (TemplateException e) { e.printStackTrace(); } }
3、Controller層代碼實(shí)現(xiàn)
@PostMapping("/exportSimpleWord") public void exportSimpleWord(@RequestBody Map<String,Object> param) { dangerCompareService.exportSimpleWord(param); }
總結(jié)
到此這篇關(guān)于java按照模板導(dǎo)出pdf或word文件的文章就介紹到這了,更多相關(guān)java模板導(dǎo)出pdf或word內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Resty開(kāi)發(fā)restful版本的Jfinal深入研究
這篇文章主要為大家介紹了Resty開(kāi)發(fā)restful版本的Jfinal深入研究有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-03-03Java線程池ForkJoinPool(工作竊取算法)的使用
Fork就是把一個(gè)大任務(wù)切分為若干個(gè)子任務(wù)并行地執(zhí)行,Join就是合并這些子任務(wù)的執(zhí)行結(jié)果,最后得到這個(gè)大任務(wù)的結(jié)果。Fork/Join?框架使用的是工作竊取算法。本文主要介紹了ForkJoinPool的使用,需要的可以參考一下2022-11-11基于java實(shí)現(xiàn)websocket協(xié)議過(guò)程詳解
這篇文章主要介紹了基于java實(shí)現(xiàn)websocket協(xié)議過(guò)程詳解,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2020-09-09Mybatis 數(shù)據(jù)庫(kù)連接池的實(shí)現(xiàn)示例
在Java應(yīng)用程序中,與數(shù)據(jù)庫(kù)的連接是非常昂貴的,因此,當(dāng)我們使用MyBatis進(jìn)行數(shù)據(jù)操作時(shí),需要一個(gè)連接池來(lái)分配并管理這些連接,本文主要介紹了Mybatis 數(shù)據(jù)庫(kù)連接池的實(shí)現(xiàn)示例,具有一定的參考價(jià)值,感興趣的可以了解一下2023-10-10如何讀取properties或yml文件數(shù)據(jù)并匹配
這篇文章主要介紹了如何讀取properties或yml文件數(shù)據(jù)并匹配方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2021-12-12Java Calendar類使用總結(jié)及使用實(shí)例
這篇文章主要介紹了Java Calendar類使用總結(jié)及使用實(shí)例,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2019-03-03