亲测真实有效
导出word步骤
在Vue中导出Word文档,可以使用第三方库file-saver和html-docx-js。首先需要安装这两个库:
npm install file-saver html-docx-js --save
"html-docx-js": "0.3.1","file-saver": "2.0.5",
然后在Vue组件中使用这两个库来导出Word文档:
vue
<chat-operation :info="info" @down="down" ref="chatItem"/>
js
down() {const contenterPdf = this.$refs.chatItemconst canvases = contenterPdf.querySelectorAll('canvas')const cloneDom = contenterPdf.cloneNode(true)if (canvases.length) {const cloneCanvases = cloneDom.querySelectorAll('canvas')const imgs = []canvases.forEach((canvas) => {const img = document.createElement('img')const url = canvas.toDataURL()img.src = urlimg.width = canvas.width >= 750 ? 750 : canvas.widthimg.height = canvas.height >= 560 ? 560 : canvas.heightimgs.push(img)})cloneCanvases.forEach((canvas, index) => {canvas.parentNode.replaceChild(imgs[index], canvas)})}// 过滤代码块序号元素const numberDoms = cloneDom.querySelectorAll('.number-container')numberDoms.forEach(dom => {dom.remove()})const contentHTML = cloneDom.innerHTMLconst content = `<!DOCTYPE html><html lang='en'><head><meta charset='UTF-8'></head><body>${contentHTML}</body></html>`const html = htmlDocx.asBlob(content, { orientation: 'portrait', pageSize: 'A4' })FileSaver.saveAs(html, `导出文件.docx`)},