vue前端html导出word⽂档1、index.html⽂件内引⼊
1<script src="<%= BASE_URL %>js/html-docx.js"></script>
2、在导出页⾯加⼊⽅法
1// 导出 word ⽂档
2 exportDocx() {
3// 克隆报告HTML
4 let contentDocument = $.clone(this.$port);
7
8 let content = `<!DOCTYPE html><html>
9 <head>
10 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
11 </head>
12 <body>
13 ${contentDocument.innerHTML}
14 </body>
15 </html>`;
16 console.log(content);
17 let converted = htmlDocx.asBlob(content);
18 saveAs(converted, `${this.title}.docx`);
19
20let link = ateDownloadLink(converted, `${this.title}.docx`);
21
22this.$refs.downloadArea.innerHTML = "";
23this.$refs.downloadArea.appendChild(link);
24 },
25
26// 转换图⽚为 base64 (todo: 有可能因跨域报错)
27 convertImagesToBase64(contentDocument) {
28// 到所有的图⽚
29 let imgs = contentDocument.querySelectorAll("img");
30
31// 图⽚转换⽤
32 let canvas = ateElement("canvas");
33 let ctx = Context("2d");
34
35 imgs.forEach((img, i) => {
36if (img.src.startsWith("data:image")) return;
37
38// img表现尺⼨
39 let realWidth = parseInt(img.style.width);
40 let realHeight = parseInt(img.style.height);
41
42// 清空画布并调整为 img 的⼤⼩
43 ctx.clearRect(0, 0, canvas.width, canvas.height);
44 canvas.width = realWidth;
45 canvas.height = realHeight;
46
47// 画图⽚到画布
48 ctx.drawImage(
49 img,
50 0,
51 0,
52 img.width,
53 img.height,
54 0,
55 0,
56 realWidth,
57 realHeight
58 );
59// ctx.drawImage(img, 0, 0);
60
61// 画布转为 base64
62 let dataURL = DataURL();
63 img.setAttribute("src", dataURL);
64 });
65
66 ve();
67 },
68
69 convertChartsToBase64(contentDocument) {
70// 到所有的图表(echart)
71 let canvases = contentDocument.querySelectorAll("canvas");
72
73// 遍历图表,转换为 base64 静态图⽚
74 canvases.forEach((canvas, i) => {
75 let echart = this.$refs.chart[i];
76 let url = DataURL();
77 let img = ateElement("img");
78 img.src = url;
79 placeChild(img, canvas);
80 });
81 },
82
83// ⽣成下载链接
84 createDownloadLink(fileObj, fileName) {
85 let link = ateElement("a");
86 link.href = ateObjectURL(fileObj);
87 link.download = fileName || "document.docx";
88 link.ateTextNode("如果没有⾃动下载,点这⾥")); 89return link;
90 },
3、需要导出的元素添加 ref="report"
4、导出按钮旁加⼀个元素
1<span ref="downloadArea"></span>
问题:导出word会没有格式。
解决办法:
⽅法⼀:需要导出的html写成内联样式
⽅法⼆、使⽤law-loader内联插件
1.安装插件
2.写⼀个样式⽂件
3.在页⾯的script标签中引⼊
var reportCss = require("raw-loader!./");
4.导出⽅法代码改成
// 导出 word ⽂档
exportDocx() {
// 克隆报告HTML
let contentDocument = $.clone(this.$port);
let content = `<!DOCTYPE html><html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <style>
${reportCss}
</style>
</head>
<body>
${contentDocument.innerHTML}
</body>
</html>`;
let converted = htmlDocx.asBlob(content);
saveAs(converted, "xxxx.docx");
let link = ateDownloadLink(converted, "xxxx.docx");
this.$refs.downloadArea.innerHTML = "";
this.$refs.downloadArea.appendChild(link);前端html
},
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论