插件推荐 | html文本转docx文档
2020-03-03 本文已影响0人
格致匠心
最近在项目中遇到一个需求,需要转化html文本为docx文档。
之前在网上有人推荐使用html-docx-js。但是这个包的last publish是在4年前,用的语言是CoffeeScript,而且构建出来的代码包括with
语句,所以在主流的现代框架中(vue/react/angular)中使用不了(它们目前的构建工具都默认启用了严格模式),我看了下Issue,发现很多都在抱怨这个包目前用不了,所以萌生了用typescript重写的想法。
目前,大家可以通过npm install html-docx-js-typescript --save-dev
来安装这个html-docx-js-typescript包,使用的方法也很简单。
import { asBlob } from 'html-docx-js-typescript'
// 要保存这个docx文件推荐引入file-saver哦,你可以用npm i -D file-saver来安装
import { saveAs } from 'file-saver'
const htmlString = `<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<h1>Welcome</h1>
</body>
</html>`
export default {
methods: {
saveDocx() {
const fileData = asBlob(htmlString).then(data => {
saveAs(fileData, 'file.docx') // 保存为docx文件
}) // asBlob() 返回 Promise<Blob|Buffer>,用promise.then还是async语法都行
},
},
}
也可以添加导出的选项,包括边距,页面的横竖之类的。
// landscape就是横着的,portrait是竖着的,默认是竖屏portrait。
const data = await asBlob(htmlString, { orientation: 'landscape', margins: { top: 100 } })
在node平台你可以用fs
模块直接把数据写入文件。
如果你把这个包用于typescript环境,当你要给导出选项暂存在一个独立的Object里,再填到参数那里的话,typescript可能会抛出类型错误。
import { asBlob } from 'html-docx-js-typescript'
const opt = {
margin: {
top: 100
},
orientation: 'landscape' // type error: because typescript automatically widen this type to 'string' but not 'Orient' - 'string literal type'
}
await asBlob(html, opt)
这是一个typescript存在的问题,可以查看github typescript仓库的issue:Syntax for hinting literal type inference #10195。
要解决它很简单,只需要给它一个类型断言就行了。
const opt = {
margin: {
top: 100
},
orientation: 'landscape' as const
}
最后,如果大家觉得我那里写得不好需要改进,欢迎提issue或者pull requests,这是项目的github地址:https://github.com/caiyexiang/html-docx-js-typescript
一起讨论,一起进步哈!