亲测真实有效

导出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

import FileSaver from 'file-saver'
import htmlDocx from 'html-docx-js/dist/html-docx'
down() {
      const contenterPdf = this.$refs.chatItem
      const 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 = url
          img.width = canvas.width >= 750 ? 750 : canvas.width
          img.height = canvas.height >= 560 ? 560 : canvas.height
          imgs.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.innerHTML

      const 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`)
    },
Logo

DAMO开发者矩阵,由阿里巴巴达摩院和中国互联网协会联合发起,致力于探讨最前沿的技术趋势与应用成果,搭建高质量的交流与分享平台,推动技术创新与产业应用链接,围绕“人工智能与新型计算”构建开放共享的开发者生态。

更多推荐