前端html转word中的一种实现方案(docxtemplater)
前言:
此方案是根据如下多个帖子,项目实践中总结糅合而成,感谢如下
https://blog.youkuaiyun.com/qq_41615323/article/details/109235888
http://markswindoll.github.io/jquery-word-export/
https://github.com/eligrey/FileSaver.js/
以上是直接导出,因为有很多的样式和导出的格式不兼容,我只仅作参考
下面两篇文章,使用了docxtemplater组件
https://www.jianshu.com/p/b3622d6f8d98
https://www.jianshu.com/p/0de31429b12a
https://www.cnblogs.com/redRun/p/14710431.html
使用docxtemplater组件进行导出的流程是,将数据直接插入到已经制作好的word模板对应的插值处,可以极大的保留word的样式和规格
需求:客户对数据表单进行填写,然后导出成word报告,因为有些样式和板块是固定的,比如说页眉页脚的logo,描述信息等,相当于要做的就是将用户数据填充到word中对应位置。如下图,就是将其中的一些图片信息和描述信息放到对应模块(Test photos)下
吐槽:我是后端向,但是被抓包去做项目前端,不是很专业,所以找最简单的方式去做html转word的导出,说不定有更好的方法,但是我写这个贴子只是为了提供一个参考。
这个功能中docxtemplater插件是核心 https://docxtemplater.com/
官网有很多使用的demo和错误处理方案,推荐做的时候可以看看
我的项目是vue2构建的,vuex做数据的管理
起步:安装对应依赖
// 安装 docxtemplater
cnpm install docxtemplater pizzip --save
// 安装图片模块,用于支持图片的导出(有需求就使用)
cnpm install docxtemplater-image-module-free
// 安装 jszip-utils
cnpm install jszip-utils --save
// 安装 jszip
cnpm install jszip --save
// 安装 FileSaver
cnpm install file-saver --save
我这里直接贴出我在项目中使用到的html2word.js文件,这是一个通用方法,这段代码借鉴自https://www.cnblogs.com/redRun/p/14710431.html
大家可以去看看
import Docxtemplater from 'docxtemplater'
import ImageModule from 'docxtemplater-image-module-free' //需要就导入
import PizZip from 'pizzip'
import JSZipUtils from 'jszip-utils'
import { saveAs } from 'file-saver'
export function exportWordAndImage(report) {
var templateChose = process.env.VUE_APP_PUBLIC_PATH + '/template.docx'//模板推荐放在public文件夹下
JSZipUtils.getBinaryContent(templateChose, function(error, content) {
if (error) {
console.error(error)
return
}
var opts = {}
opts.centered = false
opts.getImage = function(tagValue) {
return new Promise(function(resolve, reject) {
JSZipUtils.getBinaryContent(tagValue, function(error, content) {
if (error) {
return reject(error)
}
return resolve(content)
})
})
}
// 图片有关代码,没有图片的可以删除
opts.getSize = function(img, tagValue, tagName) {
// return [200, 200] // 图片大小 (固定的)如果你的图片大小要固定,请使用这行代码,将下面return new Promise的那部分注销掉
// 非固定(这里是设置宽度最大为300px的图片)
let wid = 300
return new Promise(function(resolve, reject) {
var image = new Image()
image.src = tagValue
let imgWidth, imgHeight, scale
image.onload = function() {
imgWidth = image.width
imgHeight = image.height
scale = 0
if (imgWidth > wid) {
scale = wid / imgWidth
imgWidth = wid
imgHeight = imgHeight * scale
}
resolve([imgWidth, imgHeight])
}
image.onerror = function(e) {
console.log('img, tagName, tagValue : ', img, tagName, tagValue)
reject(e)
}
})
}
var imageModule = new ImageModule(opts)
var zip = new PizZip(content)
var doc = new Docxtemplater()
.loadZip(zip)
.setOptions({ linebreaks: true }) // 换行确认,如果你有的文本中有换行符的话,可以选择她导入到word起不起作用
.attachModule(imageModule)
.compile()
doc
.resolveData(
{
// 这是你导入的数据,这个数据体中的属性或对象一定要和word模板中的插值一样
...report
}
)
.then(function() {
console.log('Export...')
doc.render()
var out = doc.getZip().generate({
type: 'blob',
mimeType: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'
})
// 输出文档,可以自定义自己的文档名
saveAs(out, 'Temporary, you need to sync as.docx')
})
})
}
使用:以下是一段vue代码中的js代码片段,基本用来介绍如何使用
<script>
import { exportSignOffPaperWord } from '@/utils/html2word'
export default {
data() {
return {
// the data for export word,这是用于导出的数据集,一般数据量少的话,可以不用单独列一个数据集出来,可以直接用annoyData,如果数据量大或者结构复杂推荐整一个专门用于导出的数据集
report: {
NowTime: '',
imgData: []
},
// 模拟一下后端数据格式
annoyData: {
NowTime: '2022/2/2',
someData: [{
img: 'data:image/jpg;base64,iVBORw...'
describe: 'test 1'
},{
img: 'data:image/jpg;base64,iVBORw...'
describe: 'test 1'
}]
}
}
},
methods: {
// export word
outWord() {
/*将数据格式化,对于imgData这种图片和描述信息的集合很大程度上需要格式化一下数据,根据你后端传递
过来的json数据再次进行一次格式化,用以适配word中的循环,当然目前例子中的这个imgData直接让annoyData
中的someData给他赋值就可以了,只要保证是个标准的Array就可以*/
this.report.imgData = this.formatData(this.annoyData.someData)
exportSignOffPaperWord(this.report)
},
formatData(IMGS) {
const IMGS_Array = []
for (const key in IMGS) {
const object_value = {}
object_value['TestPhoto'] = IMGS[key].img
object_value['TestPhoto_Title'] = IMGS[key].describe // 这个是图片描述
IMGS_Array.push(object_value)
}
return IMGS_Array
}
}
}
他们在word模板中的体现,其中{xxx}用于插入值,{%xxx}用于插入图片,{#xxx}{/xxx}用于开始和结束循环,在模板中可以对其使用word中的样式,导出的时候也能映射到对应文本上,比如我使用了文本框将其图片和标题框出来,最后就能制作成像第二张图分列显示的样子
同理,对于表格,也是类似的操作
注意,这个模板最好存放在最外层的public中,不然你很有可能会遇到Can't find end of central directory : is this a zip file ?
还有就是word模板制作过程中,每次对word模板有操作的时候,一定要保存一份之前能够成功导出的模板,不然出了问题真的很难找。这个组件感觉很适合做一些报表和签收单之类的文档。
最后,感谢本文中所有提到过的帖子,没有你们,我就寄了😊