使用工具:html-docx
优势:图片、图表能直接预览并转为base64导出,省去后端难以实现图表的生成后插入的麻烦
劣势:适合一些简单的word模板导出(比如只有标题正文简单的表格图表图片的文档),复杂的可以直接忽略。比如:纸张大小、纸张方向、css大部分样式等等(经本人试验导出无法生成,如有大佬可以配置实现欢迎指正)
下载引入
npm install html-docx-js
npm install file-saver
// 引入
import htmlDocx from 'html-docx-js/dist/html-docx'
import saveAs from 'file-saver'
在创建的盒子内完成html代码
<div class="export-box">
<!-- html -->
</div>
<button @click="gohtml">生成word</button>
生成word导出参考https://blog.csdn.net/Liuer_Qin/article/details/124799876
gohtml() {
const app = document.querySelector('.export-box')
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(() => {
this.convertImagesToBase64(cloneApp)
// console.log(document.head.outerHTML)
const converted = htmlDocx.asBlob(`