一、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)文章來(lái)源:http://www.zghlxwxcb.cn/news/detail-738447.html
/**
* 導(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)文章來(lái)源地址http://www.zghlxwxcb.cn/news/detail-738447.html
@PostMapping("/exportSimpleWord")
public void exportSimpleWord(@RequestBody Map<String,Object> param) {
dangerCompareService.exportSimpleWord(param);
}
到了這里,關(guān)于java按照模板導(dǎo)出pdf或者word的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!