vue 中将 html 中内容转换为 word 文档导出,无需模板,可以导出 echarts 图表。
使用 html-docx-js、file-saver 。
先将html中内容获取,之后将页面上的元素转成图片,然后把图片放到word文件中进行导出。
参考链接:https://blog.csdn.net/weixin_47494533/article/details/137018678
https://www.jb51.net/javascript/300311dk9.htm
1、引用
1 2 |
|
2、创建 exportToWord.js,添加导出方法
// exportToWord.js
import htmlDocx from 'html-docx-js/dist/html-docx';
import saveAs from 'file-saver';
/**
* 导出html为word
* @param fileName 导出文件名
* @param elementClass 导出块的class
*/
export function exportToWord(fileName, elementClass) {
//.export-box 需要转word的最大dom盒子的类名
const app = document.querySelector(elementClass);
const cloneApp = app.cloneNode(true);
const canvases = app.getElementsByTagName('canvas');
const cloneCanvases = cloneApp.getElementsByTagName('canvas');
const promises = Array.from(canvases).map((ca, index) => {
return new Promise((res) => {
const url = ca.toDataURL('image/png', 1);
const img = new Image();
img.onload = () => {
URL.revokeObjectURL(url);
res();
};
img.src = url;
// 生成img插入clone的dom的canvas之前
cloneCanvases[index].parentNode.insertBefore(
img,
cloneCanvases[index],
);
});
});
// 移除原来的canvas
const cloneCanvas = cloneApp.getElementsByTagName('canvas');
Array.from(cloneCanvas).forEach((ca) => ca.parentNode.removeChild(ca));
Promise.all(promises).then(() => {
convertImagesToBase64(cloneApp);
const converted = htmlDocx.asBlob(`
<html xmlns:o=\'urn:schemas-microsoft-com:office:office\' xmlns:w=\'urn:schemas-microsoft-com:office:word\' xmlns=\'http://www.w3.org/TR/REC-html40\'>
<head>
<style>
${document.head.outerHTML}
</style>
</head>
<body>
${cloneApp.outerHTML}
</body>
</html>`);
saveAs(converted, fileName);
});
}
/**
* 将image转换成base64
* @param cloneApp
*/
function convertImagesToBase64(cloneApp){
let regularImages = cloneApp.getElementsByTagName('img');
let canvas = document.createElement('canvas');
let ctx = canvas.getContext('2d');
for (let index = 0; index < regularImages.length; index++) {
canvas.width = regularImages[index].width;
canvas.height = regularImages[index].height;
ctx.drawImage(
regularImages[index],
0,
0,
regularImages[index].width * 0.8,
regularImages[index].height * 0.8,
);
let ext = regularImages[index].src
.substring(regularImages[index].src.lastIndexOf('.') + 1)
.toLowerCase();
let dataURL = canvas.toDataURL('image/' + ext);
regularImages[index].setAttribute('src', dataURL);
}
canvas.remove();
}
3、调用方法
<template>
<div>
<div>
<el-row>
<button type="button" @click="exportWord1">导出word</button>
</el-row>
<div id="contentDom" style="text-align: center" class="export-box">
<div>内容</div>
</div>
</div>
</div>
</template>
<script>
import { exportToWord } from '@/utils/feature/exportToWord';
export default {
name: "exportToWord",
data() {
return {
}
},
methods: {
// html转为word
exportWord1() {
exportToWord('test.docx', '.export-box');
},
}
}
</script>
<style scoped>
</style>
补充:发布到线上后发现,导出word时css失效,发现css样式写在页面中,编译打包时应该是进行了转换之类的。
最后将css放入公共文件夹,public/index.html中可以了。