使用html-docx-js + fileSaver实现前端导出word

因为html-docx-js是16年的老库了,它代码里面用到的with语法现在严格模式不允许,用npm直接引入会报错,所以我们需要用其它方式引入

首先要将html-docx-js的代码放到项目中

html-docx-js/dist/html-docx.js at master · evidenceprime/html-docx-js · GitHub

我这边的vue项目,所以放到public文件下

代码里面几个with的用法需要改一下,因为现在都是默认严格模式了

全局搜一下with(,然后把涉及到的都改成类似如下的即可

接下来到项目的html文件中,使用script标签引入

如果使用typescript,需要声明一下全局变量

TypeScript 复制代码
export declare global {
  interface Window {
    htmlDocx: any
    saveAs: (doc: any, name: string) => void
  }
}

这样子就可以在项目中愉快的使用了~使用方法如下:

TypeScript 复制代码
// 需要打印的dom元素
const areaRef = ref()

const handleDownload = () => {
  const cssText = `
    th, td {
      border-color: red;
    }
  `
  const content = `
    <!DOCTYPE html>
    <html>
      <head>
        <style>
          ${cssText}
        </style>
      </head>
      <body>
        ${areaRef.value.outerHTML}
      </body>
    </html>
  `
  const converted = window.htmlDocx.asBlob(content, {
    orientation: 'landscape',
  })
  window.saveAs(converted, 'test.docx')
}

PS:如果遇到样式问题的话,比如图片宽高(需要使用img标签的width和height属性),字体大小(需要使用pt)不生效的话,可以先把对应的docx模板转成html查看样式后再对应进行修改

相关推荐
C澒2 分钟前
Remesh 框架详解:基于 CQRS 的前端领域驱动设计方案
前端·架构·前端框架·状态模式
Charlie_lll5 分钟前
学习Three.js–雪花
前端·three.js
onebyte8bits22 分钟前
前端国际化(i18n)体系设计与工程化落地
前端·国际化·i18n·工程化
C澒31 分钟前
前端分层架构实战:DDD 与 Clean Architecture 在大型业务系统中的落地路径与项目实践
前端·架构·系统架构·前端框架
BestSongC35 分钟前
行人摔倒检测系统 - 前端文档(1)
前端·人工智能·目标检测
0思必得01 小时前
[Web自动化] Selenium处理滚动条
前端·爬虫·python·selenium·自动化
Misnice1 小时前
Webpack、Vite、Rsbuild区别
前端·webpack·node.js
青茶3601 小时前
php怎么实现订单接口状态轮询(二)
前端·php·接口
觉醒大王2 小时前
哪些文章会被我拒稿?
论文阅读·笔记·深度学习·考研·自然语言处理·html·学习方法
大橙子额2 小时前
【解决报错】Cannot assign to read only property ‘exports‘ of object ‘#<Object>‘
前端·javascript·vue.js