需求:根据经费申请表的id去动态填充经费申请表的内容,并进行预览打印。
点击之后
大概流程就是这样子
0.大致流程
前端点击打印向后端发送请求--》后端进行word模板数据的填充,并转换为pdf格式,返回文件流--》前端接受文件流进行预览打印处理
1.后端实现
1.1.控制器层
@GetMapping("/getSafeDoc")
public JSONObject getSafeDoc(HttpServletRequest request, HttpServletResponse response,@RequestParam("id") int id) throws IOException {
this.baseService.getSafeDoc(response.getOutputStream(),id);
return resultSuccess();
}
1.2.业务层
public void getSafeDoc(ServletOutputStream writer,int id) {
// 这里去数据库去获取需要填充到模板中的数据
Record first = dbPro.findFirst("SELECT f.*,p.* FROM safeApplicationFunding f LEFT JOIN safeApplicationProcess p ON f.id=p.applicantsFundingId WHERE f.id=" + id);
try {
// 创建一个文档对象
Document doc = new Document();
// 读取模板
doc.loadFromFile("D:\\JetBrains\\ideaIU-2021.1\\ym_sbjx\\DDMProduct\\DDMSysTem\\src\\main\\java\\com\\ddm\\business\\securityManage\\safe\\demo.docx");
// 替换文档中的内容
doc.replace(Pattern.compile("projectName"),first.getStr("projectName"));
doc.replace(Pattern.compile("applicationFee"),first.getStr("applicationFee"));
doc.replace(Pattern.compile("reason"),first.getStr("reason"));
doc.replace(Pattern.compile("applicationUser"),first.getStr("applicationUser"));
doc.replace(Pattern.compile("(.*)"+first.getInt("type")+"/."),"(**)");
// 转换为pdf并给响应流中写入数据
doc.saveToStream(writer, FileFormat.PDF);
doc.close();
} catch (Exception ex) {
// string msg = ex.Message;
}
}
2.前端实现
2.1.vue方法
// 打印主方法
dy(id){
this.getFile(id).then(result => {
const binaryData = [];
binaryData.push(result.data);
//获取blob链接
let pdfUrl = window.URL.createObjectURL(
new Blob(binaryData, { type: "application/pdf" })
);
if (pdfUrl) {
this.handlePrint(pdfUrl);
}
})
},
// 调用打印预览功能
handlePrint(pdf) {
if (document.getElementById("print-iframe")) {
document.body.removeChild(document.getElementById("print-iframe"));
}
//判断iframe是否存在,不存在则创建iframe
let iframe = document.getElementById("print-iframe");
if (!iframe) {
iframe = document.createElement("IFRAME");
let doc = null;
iframe.setAttribute("src", pdf);
iframe.setAttribute("id", "print-iframe");
document.body.appendChild(iframe);
doc = iframe.contentWindow.document;
doc.close();
iframe.contentWindow.focus();
}
iframe.contentWindow.print();
},
// 从后端获取文件流
getFile(id) {
return this.axios({
method: "GET",
url: this.baseUrl+"/getSafeDoc?id=" + id,
headers: { 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8' },
responseType: 'arraybuffer', //一定要设置响应类型,否则页面会是空白pdf
});
},