注意:这里使用的word是docx格式的doc的不行

后端:

pom.xml

<!-- excel工具 -->
<dependency><groupId>org.apache.poi</groupId><artifactId>poi-ooxml</artifactId>
</dependency>

写的工具替换类(从CSDN上找的,原博客找不到了,我在此基础上改动了一些)

package com.xxx.common.utils.poi;import com.xxx.common.utils.StringUtils;
import org.apache.poi.xwpf.usermodel.*;import java.io.*;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;/*** @author csdn* 替换word文字*/
public class ReplaceWordUtil {/*** 替换表格内的文字* @param data* @param sourceFilePath* @return* @throws Exception*/public static XWPFDocument replaceInTable(Map<String, Object> data ,String sourceFilePath) throws Exception {File file = new File(sourceFilePath);if(!file.exists()){throw new Exception("文件不存在!");}XWPFDocument document = new XWPFDocument(new FileInputStream(file));replaceTableValue(document,data);return document;}/*** 替换表格内的文字* @param document* @param data*/public static void replaceTableValue(XWPFDocument document,Map<String, Object> data){//重构mapbuildMap(data);Iterator<XWPFTable> tableList = document.getTablesIterator();XWPFTable table;List<XWPFTableRow> rows;List<XWPFTableCell> cells;while (tableList.hasNext()) {table = tableList.next();if (!checkText(table.getText())) {continue;}rows = table.getRows();for (XWPFTableRow row : rows) {cells = row.getTableCells();for (XWPFTableCell cell : cells) {if (!checkText(cell.getText())) {continue;}List<XWPFParagraph> paragraphs = cell.getParagraphs();for (XWPFParagraph paragraph : paragraphs) {replaceValue(paragraph, data);}}}}}/*** 构造map,不再用外部替代了* @param data*/public static void buildMap(Map<String, Object> data) {Iterator<Map.Entry<String, Object>> iterator = data.entrySet().iterator();Map<String, Object> newMap = new HashMap<>(data.size());while (iterator.hasNext()) {Map.Entry<String, Object> entry = iterator.next();String newKey = "${" + entry.getKey() + "}";newMap.put(newKey, entry.getValue());iterator.remove();}data.putAll(newMap);}/*** 检查文本中是否包含 ${* @param text* @return*/public static boolean checkText(String text) {return text.indexOf("${") != -1;}/*** 替换内容* @param paragraph* @param textMap*/public static void replaceValue(XWPFParagraph paragraph, Map<String, Object> textMap) {XWPFRun run, nextRun;String runsText;List<XWPFRun> runs = paragraph.getRuns();for (int i = 0; i < runs.size(); i++) {run = runs.get(i);runsText = run.getText(0);if (StringUtils.isEmpty(runsText)) {continue;}if (!checkText(runsText)) {continue;}while (!runsText.contains("}")) {nextRun = runs.get(i + 1);runsText = runsText + nextRun.getText(0);//删除该节点下的数据paragraph.removeRun(i + 1);}if (textMap.containsKey(runsText)) {run.setText(textMap.get(runsText).toString(), 0);} else {//如果匹配不到,则塞入空run.setText("", 0);}}}
}

word模板(注意一定要是docx的)

后端接口请求和处理:

 @GetMapping("/getXXXXX")public void getXXX(HttpServletResponse response){try {XXXX xxxx= sqService.getById(12013);//这里转为map,去进行匹配Map data = JSON.parseObject(JSON.toJSONString(xxxx), Map.class);XWPFDocument xwpfDocument = ReplaceWordUtil.replaceInTable(data, 你模板的路径);response.setContentType("application/msword");response.setCharacterEncoding("utf-8");xwpfDocument.write(response.getOutputStream());}catch (Exception e){System.out.println(e);}}

前端:

下载插件:

 npm install docx-previewnpm install jszip#需要打印的再下载这个npm install vue-print-nb --save

接口请求:

这里主要就写几个页面用到的功能

// 页面
<template><div class="app-container">//这个打印我就不多说了,需要打印的自行下载 v-print<el-button v-print="'#printWord'"> 打 印 </el-button><div ref="word" id="printWord"></div></div>
</template>引入axios
import axios from 'axios'//从后台获取数据的方法showWord(){const docx = require("docx-preview");axios.get(this.wordUrl, {responseType: "blob"}).then((res) => {const blob = new Blob([res.data]);docx.renderAsync(blob, this.$refs.word).then(this.print(this.$refs.word));});},

效果展示:

打印效果展示

--------------------------------------------------------------------------------------

因为前端展示的是转换为html后的数据,所以展示之前填充的数据位置都不准了,现修改为word转换为图片进行打印和展示

pom:

        <dependency><groupId>e-iceblue</groupId><artifactId>spire.doc.free</artifactId><version>5.2.0</version></dependency>

代码:

    @GetMapping("/getXXXX")public String getXXX(XXX) {try {xxxxx byId = sqService.getById(12014);Map data = JSON.parseObject(JSON.toJSONString(byId), Map.class);XWPFDocument xwpfDocument = ReplaceWordUtil.replaceInTable(data, "模板路径");//将word 写入流ByteArrayOutputStream wordDocument = new ByteArrayOutputStream();xwpfDocument.write(wordDocument);//读取之前的流InputStream inputStream = new ByteArrayInputStream(wordDocument.toByteArray());Document document = new Document();document.loadFromStream(inputStream,FileFormat.Docx);//选择word的第一页进行转换为图片BufferedImage bufferedImage = document.saveToImages(0, ImageType.Bitmap);ByteArrayOutputStream imgOutStream = new ByteArrayOutputStream();ImageIO.write(bufferedImage, "PNG", imgOutStream);BASE64Encoder encoder = new sun.misc.BASE64Encoder();String trim = encoder.encodeBuffer(imgOutStream.toByteArray()).trim();String s = trim.replaceAll("\n", "").replaceAll("\r", "");return "data:image/png;base64,"+s;} catch (Exception e) {System.out.println(e);}return null;}

后端返回的是base64的图片,前端怎么展示就不用多说了吧

--------------------------------------------------------------------------------------------------

接下来看似完成了,但因为是word转成图片展示的,导致清晰度不够高,那怎么办?是使用图片清晰化?还是什么?

我的建议是将word转为pdf后文件存放在本地,通过配置negix映射使用浏览器访问打开并打印

    @GetMapping("/getXXXX")public String getXXX(XXX) {try {xxxxx byId = sqService.getById(12014);Map data = JSON.parseObject(JSON.toJSONString(byId), Map.class);XWPFDocument xwpfDocument = ReplaceWordUtil.replaceInTable(data, "模板路径");String sendPdfName =  UUID.randomUUID() +".pdf";File file = new File(文件夹路径);if(!file.isDirectory()){file.mkdirs();}//直接将word转为pdf存储,并返回文件名WordUtil.wordToPdf(xwpfDocument,xxxxConfig.getTempFilePath() + sendPdfName);return sendPdfName;} catch (Exception e) {System.out.println(e);}return null;}
package com.xxx.common.utils.poi;import com.spire.doc.Document;
import com.spire.doc.FileFormat;
import com.spire.doc.documents.ImageType;
import org.apache.poi.xwpf.usermodel.XWPFDocument;import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.util.Base64;/*** word工具类*/
public class WordUtil {/*** 将word 转为pdf 并返回pdf 的名字* @param xwpfDocument* @param path* @return* @throws Exception*/public static void wordToPdf(XWPFDocument xwpfDocument,String path) throws Exception{ByteArrayOutputStream wordDocument = new ByteArrayOutputStream();xwpfDocument.write(wordDocument);InputStream inputStream = new ByteArrayInputStream(wordDocument.toByteArray());com.spire.doc.Document document = new Document();document.loadFromStream(inputStream, FileFormat.Docx);document.saveToFile(path,FileFormat.PDF);}
}

接着就是在negix内配置 你 xxxxConfig.getTempFilePath() 这个在服务器的路径了

location /tempFilePath/{alias D:/xxx/temp/xx/;}

接着只需要在你前端代码里接收返回时,用浏览器打印就完事了,记得用google浏览器啊

xxxx(query).then(rep =>{if (rep) {window.open("/tempFilePath/" + rep, "_blank");} else {this.$message.error("打印出错!");}})

word模板替换加前台vue展示word并打印相关推荐

  1. 用Excel模板进行数据导出加前台vue展示excel并打印

    前言: 找了好多资料,基本都是需要页面上写好table再获取数据进行展示或者将其转为pdf再页面展示,我不想这样做于是想了好久,在翻来翻去的时候无意间发现了WorkSheet的一个方法叫做 saveT ...

  2. java word模板替换多行_java poi word模板替换段落的换行显示

    在poi操作word模板进行数据替换时,会存在替换的段落需要换行的情况,由于传入的都是字符串,之前在网上搜索过一些处理方法都没有效果,如给字符串添加:"\r","\r\n ...

  3. java word模板替换多行_Java动态替换word模板的最佳实践

    poi-tl 基于word的模板渲染(替换)组件 对docx格式的文档增加模板语法,增加渲染模板的方便性,目前支持对段落.页眉.页脚.表格的文本.图片.表单渲染. 对于word模板替换,我们不仅要考虑 ...

  4. 跨平台POI处理word模板替换、转pdf

    2019独角兽企业重金招聘Python工程师标准>>> 实现跨平台Java处理word模板替换,包括标签替换文字.标签替换图片.设置文字样式.图片大小,word转pdf(借助Open ...

  5. Word文档在前台页面展示

    这篇文章主要是围绕如何实现Word文档在页面上进行预览,以及涉及到相关的技术点,和我们将会在这个功能上使用的插件. 插件:Aspose.Total: Aspose.Total是Aspose公司旗下的最 ...

  6. C#读取Word模板替换相应的字符串(标签)生成新的Word

    在平常工作中,生成word的方式主要是C#读取html的模板文件处理之后保存为.doc文件,这样的好处是方便,快捷,能满足大部分的需求.不过有些特殊的需求并不能满足,如要生成的Word为一个表格,只是 ...

  7. itext word模板替换_【极简Python 自动化办公】Python写入Word文档

    [极简Python 自动化办公]专栏是介绍如何利用python办公,减少工作负荷.篇幅精炼,内容易懂,无论是否有编程基础,都非常适合. 在上次文章中,我们学习了[用python写入excel],这次我 ...

  8. 【PHPWord】基于Word模板替换生成输出表格动态生成内容、合并单元格、设置单元格背景颜色

    文章目录 一.前言 二.业务需求 三.功能实现 1.处理数据 2.Word模板 3.输出动态数据 四.完整代码和模板 1.Word模板 2.完整代码 五.总结 一.前言 在之前的文章中,我们做了直接生 ...

  9. freemaker生成word模板的各种坑,包含word打不开、批量添加图片、图片变形等问题总结

    最近在使用freemaker做一个word模板,里面包含大量表格.截图.超链接等数据.历时一周多,遇到很多坑,现在想想都后怕,现在简单总结一下,希望给以后的小伙伴提供帮助,少走弯路! 坑一:word打 ...

最新文章

  1. MYSQL数据库导入数据时出现乱码的解决办法
  2. 修改默认的pip版本为对应python2.7
  3. Android之万能适配器Adapter的使用
  4. Python 读取json文件
  5. SQL Server Audit(审核)配置方法--数据库级别的审核
  6. 适用于苹果Mac的 4 个好用的 CAD 软件
  7. 吉他指弹入门——日式指弹的pm技巧
  8. 杂牌平板mt6797_联发科MT6797炸现跑分库 强得令人毛骨悚然
  9. 从12306帐号泄漏谈用户密码安全
  10. 淘宝下架苹果iOS充值业务,马云或在为支付宝扫除障碍
  11. 求两个数的最大公约数(辗转相减法)
  12. 服务器项目迁移本地,云服务器迁移本地
  13. 同一局域网内的其他电脑访问我的电脑本地的网站
  14. 奇虎360退出美国股市 12月再曝拟私有化
  15. Google怎么赚钱(转)
  16. 湖北汽车工业学院c语言,第六届C语言程序设计颁奖典礼举行
  17. DreamWeaver2020下载安装
  18. uniapp 全端小程序接入广告
  19. JAVA火影忍者究极冲击_火影忍者究极冲击
  20. MOS管的密勒效应开通关断损耗分析

热门文章

  1. 英语作文提示(持续更新)
  2. Linux版phpstudy中开启目录浏览功能
  3. Excel 突显光标所在行列
  4. linux 电脑远程连接wifi,Linux系统下安装mosh来远程连接另一台Linux主机
  5. Spotify终止创作者上传音乐计划
  6. 数据分析从入门到进阶的最优路径
  7. Java过滤器链原理解析
  8. 使用OpenCV实现哈哈镜效果
  9. 【windows设置屏幕拓展《Twomon SE》】
  10. 按揭房贷款需要注意哪些事项