java按照模板導出pdf或word文件詳細代碼
一、java按照模板導出pdf
(一)制作模板
1、在word里制作模板
因為PDF常用的軟件不支持編輯,所以先用Word工具,如WPS或者Office新建一個空白Word文檔,里面制作出自己想要的樣式。

2、 將Word轉換成PDF形式
將設置好的Word文檔轉換成PDF形式,保存起來。

3、編輯PDF準備表單
用Adobe Acrobat DC 軟件打開保存好的PDF模板文件,點擊右側的準備表單按鈕


接下來進行數據源配置,在要顯示圖像的區(qū)域,點擊鼠標右鍵,選擇文本域,設定好圖像的顯示位置,并指定數據源字段。需要注意的是,配置的數據源字段必須與Java中的實體類對象的字段名保持一致。

配置完成之后保存pdf文件,留作模板使用。

(二)java代碼編寫
1、導入依賴
<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、實體類
import lombok.Data;
/**
* 報表實體類
*/
@Data
public class MsaBusinessVO {
/**接收業(yè)務總次數*/
private String total;
/**接收業(yè)務總次數(去年同期)*/
private String lastToatl;
/**處理次數*/
private String dealNum;
/**處理次數(去年同期)*/
private String lastDealNum;
/**已完成次數*/
private String completeNum;
/**已完成次數(去年同期)*/
private String lastCompleteNum;
/**售后次數*/
private String afterSales;
/**售后次數(去年同期)*/
private String lastAfterSales;
}3、service層代碼實現
/** * 生成報表 * @param id * @param response */ void generateMsaBusiness(String id,HttpServletResponse response) throws UnsupportedEncodingException;
@Override
public void generateMsaBusiness(String id,HttpServletResponse response) throws UnsupportedEncodingException {
//通過id獲取msaBusinessVO
MsaBusinessVO msaBusinessVO = msaBusinessDao.getMsaBusinessInfo(id);
// 模板名稱
String templateName = "msaBusiness.pdf";
String path = "/static/template/";
//String path = "";
// 獲取操作系統(tǒng)名稱,根據系統(tǒng)名稱確定模板存放的路徑
/*String systemName = System.getProperty("os.name");
if(systemName.toUpperCase().startsWith("WIN")){
path = "D:/pdf/";
}else {
path = "/usr/local/pdf/";
}*/
// 生成導出PDF的文件名稱
String fileName = "海事行政執(zhí)法業(yè)務數據統(tǒng)計"+msaBusinessVO.getStartDate()+"至"+msaBusinessVO.getEndDate()+".pdf";
fileName = URLEncoder.encode(fileName, "UTF-8");
// 設置響應頭
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é)數組流,用來緩存文件流
bos = new ByteArrayOutputStream();
// 根據模板表單生成一個新的PDF
stamper = new PdfStamper(reader, bos);
// 獲取新生成的PDF表單
AcroFields form = stamper.getAcroFields();
// 給表單生成中文字體,這里采用系統(tǒng)字體,不設置的話,中文顯示會有問題
//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);
// 裝配數據
this.setMsaBusinessToForm(form, msaBusinessVO);
// 表明該PDF不可修改
stamper.setFormFlattening(true);
// 關閉資源
stamper.close();
// 將ByteArray字節(jié)數組中的流輸出到out中(即輸出到瀏覽器)
Document doc = new Document();
PdfCopy copy = new PdfCopy(doc, out);
doc.open();
//改成這樣就不會只顯示一頁了。
PdfImportedPage importPage = null;
///循環(huá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導出成功*********************************");
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (out != null) {
out.flush();
out.close();
}
if (reader != null) {
reader.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
/**
* 裝配數據
* @param form
* @param msaBusinessVO
* @throws DocumentException
* @throws IOException
*/
public void setMsaBusinessToForm(AcroFields form,MsaBusinessVO msaBusinessVO) throws DocumentException, IOException {
form.setField("total",msaBusinessVO.getTotal());//進出港船舶總艘次
form.setField("lastTotal",msaBusinessVO.getLastTotal());//進出港船舶總艘次(去年同期)
form.setField("dealNum",msaBusinessVO.getDealNum());//進出港報告內河船艘次
form.setField("lastDealNum",msaBusinessVO.getLastDealNum());//進出港報告內河船艘次(去年同期)
form.setField("completeNum",msaBusinessVO.getCompleteNum());//進出港報告海船艘次
form.setField("lastCompleteNum",msaBusinessVO.getLastCompleteNum());//進出港報告海船艘次(去年同期)
form.setField("afterSales",msaBusinessVO.getAfterSales());//進出口岸查驗船舶艘次
form.setField("lastAfterSales",msaBusinessVO.getLastAfterSales());//進出口岸查驗船舶艘次(去年同期)
}4、Controller層代碼實現
/**
* 導出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按照模板導出word
(一)制作模板
1、word模板文件處理,如下圖所示在word 文檔中填值的地方寫入占位變量,值得注意的是,word中的占位變量要與java代碼中寫入的元素名稱保持一致。

2、將word文檔另存為xml文件,編輯如下圖,找到填寫的占位,修改為${total}格式


3、將文件后綴名改為.ftl文件 ,留作模板使用。

(二)java代碼編寫
1、引入依賴
<dependency>
<groupId>org.freemarker</groupId>
<artifactId>freemarker</artifactId>
<version>2.3.28</version>
<scope>compile</scope>
</dependency>2、service層代碼實現
/** * 導出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 {
// 要填充的數據 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");
//指定路徑的第一種方式(根據某個類的相對路徑指定)
configuration.setClassForTemplateLoading(this.getClass(), "/static/template/");
// 輸出文檔路徑及名稱
File outFile = new File("D:/附件"+new SimpleDateFormat("yyyyMMddHHmmss").format(new Date())+".doc");
//以utf-8的編碼讀取ftl文件 名字要正確,最好不要放在本地,可能會出現找不到。
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層代碼實現
@PostMapping("/exportSimpleWord")
public void exportSimpleWord(@RequestBody Map<String,Object> param) {
dangerCompareService.exportSimpleWord(param);
}總結
到此這篇關于java按照模板導出pdf或word文件的文章就介紹到這了,更多相關java模板導出pdf或word內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
Resty開發(fā)restful版本的Jfinal深入研究
這篇文章主要為大家介紹了Resty開發(fā)restful版本的Jfinal深入研究有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2022-03-03
Java線程池ForkJoinPool(工作竊取算法)的使用
Fork就是把一個大任務切分為若干個子任務并行地執(zhí)行,Join就是合并這些子任務的執(zhí)行結果,最后得到這個大任務的結果。Fork/Join?框架使用的是工作竊取算法。本文主要介紹了ForkJoinPool的使用,需要的可以參考一下2022-11-11

