纯前端实现将页面数据下载word文档中【包括图片,echarts图,表格,和对话 内容】

亲测真实有效

导出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`)
    },
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值