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

相关推荐
ShenJLLL3 小时前
vue部分知识点.
前端·javascript·vue.js·前端框架
恋猫de小郭4 小时前
你是不是觉得 R8 很讨厌,但 Android 为什么选择 R8 ?也许你对 R8 还不够了解
android·前端·flutter
PineappleCoder4 小时前
告别“幻影坦克”:手把手教你丝滑规避布局抖动,让页面渲染快如闪电!
前端·性能优化
武帝为此5 小时前
【Shell变量替换与测试】
前端·chrome
CappuccinoRose5 小时前
CSS 语法学习文档(十九)
前端·css·属性·flex·grid·学习资源·格式化上下文
雷电法拉珑5 小时前
财务数据批量采集
linux·前端·python
We་ct6 小时前
LeetCode 105. 从前序与中序遍历序列构造二叉树:题解与思路解析
前端·算法·leetcode·链表·typescript
前端 贾公子6 小时前
深入理解 Vue3 的 v-model 及自定义指令的实现原理(下)
前端·html
Roc.Chang7 小时前
Vite 启动报错:listen EACCES: permission denied 0.0.0.0:80 解决方案
linux·前端·vue·vite