使用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查看样式后再对应进行修改

相关推荐
Shi_haoliu2 小时前
openClaw源码部署-linux
前端·python·ai·openclaw
程序员小寒2 小时前
前端性能优化之白屏、卡顿指标和网络环境采集篇
前端·javascript·网络·性能优化
烛阴3 小时前
Claude CLI AskUserQuestion 工具详解:让 AI 开口问你
前端·claude
wal13145203 小时前
OpenClaw教程(九)—— 彻底告别!OpenClaw 卸载不残留指南
前端·网络·人工智能·chrome·安全·openclaw
mon_star°3 小时前
在TypeScript中,接口MenuItem定义中,为什么有的属性带问号?,有的不带呢?
前端
牛奶3 小时前
分享一个开源项目,让 AI 辅助开发真正高效起来
前端·人工智能·全栈
次顶级4 小时前
表单多文件上传和其他参数处理
前端·javascript·html
why技术4 小时前
我拿到了腾讯QClaw的内测码,然后沉默了。
前端·后端
小一梦5 小时前
宝塔面板单域名部署多个 Vue 项目:从路径冲突到完美共存
服务器·javascript·vue.js