前端直接查询后台数据打印自定义world文档

前端直接查询后台数据打印自定义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();
	});

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值