前端直接查询后台数据打印自定义world文档
此代码中新建一个world文档模板,map中存的就是需要打印的内容,在模板中用{{data}}来展示!
//打印
@RequestMapping("/printEquipDamageWorld")
@ResponseBody
public ResponseEntity<byte[]> printEquipDamageWorld(@RequestParam Map<String, Object> map, HttpServletResponse response) throws IOException {
map.put("code", "aaaa");
// Configure config = Configure.newBuilder().customPolicy("table", wordConfig).build();
String filePath = System.getProperty("user.dir") + "\\workbench-webapp\\src\\main\\resources\\static\\wordTemplate\\equipment\\equip_damage_print.docx";
XWPFTemplate template = XWPFTemplate.compile(filePath).render(map);
String temporaryWrodFileName = UUIDUtils.millis62String()+System.currentTimeMillis();
String temporaryPdfFileName = UUIDUtils.millis62String()+System.currentTimeMillis();
File f = new File(downLoadPath+ temporaryWrodFileName+".docx");
if(!f.getParentFile().exists()){
f.getParentFile().mkdirs();
}
OutputStream out = new FileOutputStream(f);
File file = null;
try{
f.createNewFile();
template.write(out);
String newPath = downLoadPath+temporaryPdfFileName+".pdf";
file = new File(newPath);
CommonUtil.word2Pdf(downLoadPath+ temporaryWrodFileName+".docx",newPath);
// 转换并返回结果
byte[] pdfFileBytes = FileUtils.readFileToByteArray(file);
HttpHeaders httpHeaders = new HttpHeaders();
httpHeaders.setContentType(MediaType.valueOf("application/pdf"));
httpHeaders.setContentLength(pdfFileBytes.length);
httpHeaders.add(HttpHeaders.ACCEPT_RANGES, "bytes");
return new ResponseEntity<byte[]>(pdfFileBytes, httpHeaders, HttpStatus.OK);
}catch (Exception e){
e.printStackTrace();
}finally {
if(out!=null){
out.close();
}
if(template !=null){
template.close();
}
if(f.exists()){
f.delete();
}
if(file!=null && file.exists() )file.delete();
}
return null;
}
将文件转化为pdf
public static void word2Pdf(String srcPath, String desPath) throws IOException {
// 源文件目录
File inputFile = new File(srcPath);
if (!inputFile.exists()) {
System.out.println("源文件不存在!");
return;
}
// 输出文件目录
File outputFile = new File(desPath);
if (!outputFile.getParentFile().exists()) {
outputFile.getParentFile().exists();
}
// 调用openoffice服务线程
String command = "cmd /k soffice -headless -accept=\"socket,host=127.0.0.1,port=8100;urp;\" -nofirststartwizard";
Process p = Runtime.getRuntime().exec(command, null, new File("C:\\Program Files (x86)\\OpenOffice 4\\program"));
// 连接openoffice服务
OpenOfficeConnection connection = new SocketOpenOfficeConnection(
"127.0.0.1", 8100);
connection.connect();
// 转换word到pdf
DocumentConverter converter = new StreamOpenOfficeDocumentConverter(connection);
converter.convert(inputFile, outputFile);
// 关闭连接
connection.disconnect();
// 关闭进程
p.destroy();
System.out.println("转换完成!");
}
前端页面src后台pdf流接口
<iframe style="display: none;" id="printIframe" src="/equipment/damage/tLaboratoryEquipmentDamage/printEquipDamageWorld"></iframe>
注释部分为下载功能
$("#printWorld").click(function () {
// var xhr = new XMLHttpRequest();
// xhr.open("GET", "/equipment/damage/tLaboratoryEquipmentDamage/printEquipDamageWorld", true); // 也可以使用POST方式,根据接口
// xhr.responseType = "blob"; // 返回类型blob
// // 定义请求完成的处理函数,请求前也可以增加加载框/禁用下载按钮逻辑
// xhr.onload = function () {
// // 请求完成
// if (this.status === 200) {
// // 返回200
// var blob = this.response;
// var reader = new FileReader();
// reader.readAsDataURL(blob); // 转换为base64,可以直接放入a表情href
// reader.onload = function (e) {
// console.log(e)
// // 转换完成,创建一个a标签用于下载
// var a = document.createElement('a');
// a.download = 'data.docx';
// a.href = e.target.result;
// $("body").append(a); // 修复firefox中无法触发click
// a.click();
// $(a).remove();
// // $("#printIframe")[0].contentWindow.print();
//
// }
// }
// };
// // 发送ajax请求
// xhr.send();
$("#printIframe")[0].contentWindow.print();
});