实现以下两点功能:
1.导出单条数据至word中,图片还需支持多张。
2.导出多条数据至zip压缩包中,并且有图片也需要导出至word中,支持多张。
废话不多说开整!
首先在mixins文件中创建一个 exportWordImage.js 代码如下:
import Docxtemplater from 'docxtemplater'
import PizZip from 'pizzip'
import JSZipUtils from 'jszip-utils'
import { saveAs } from 'file-saver'
import JSZip from 'jszip'
export default {
data () {
return {
zipName: '导出word.zip',
zip: null,
download: [],
length: 0
}
},
watch: {
download (val) {
if (val.length === this.length) {
var word = this.zip.generate({ type: 'blob' })
saveAs(word, this.zipName)
this.zip = null
this.download = []
}
}
},
methods: {
/**
* 将base64格式的数据转为ArrayBuffer
* @param {Object} dataURL base64格式的数据
*/
base64DataURLToArrayBuffer (dataURL) {
const base64Regex = /^data:image\/(png|jpg|jpeg|svg|svg\+xml);base64,/
// const base64Regex = /^data:image\/(png|jpg|svg|svg\+xml);base64,/
if (!base64Regex.test(dataURL)) {
return false
}
const stringBase64 = dataURL.replace(base64Regex, '')
let binaryString
if (typeof window !== 'undefined') {
binaryString = window.atob(stringBase64)
} else {
binaryString = Buffer.from(stringBase64, 'base64').toString('binary')
}
const len = binaryString.length
const bytes = new Uint8Array(len)
for (let i = 0; i < len; i++) {
const ascii = binaryString.charCodeAt(i)
bytes[i] = ascii
}
return bytes.buffer
},
create (res = '') {
if (res) {
this.zip = new JSZip(res)
} else {
this.zip = new JSZip()
}
},
// 导出多条数据执行这个方法
ExportWordLists (url, list) {
this.length = list.length
list.forEach((item) => {
var obj = item
this.ExportBriefDataDocxs(url, obj, item.imgData)
})
},
ExportBriefDataDocxs (tempDocxPath, data, fileName, imgSize) {
console.log('ExportBriefDataDocxs', tempDocxPath, data, fileName, imgSize)
var _this = this
// 这里要引入处理图片的插件
var ImageModule = require('docxtemplater-image-module-free')
var expressions = require('angular-expressions')
var assign = require('lodash/assign')
var last = require('lodash/last')
expressions.filters.lower = function (input) {
// This condition should be used to make sure that if your input is
// undefined, your output will be undefined as well and will not
// throw an error
if (!input) return input
// toLowerCase() 方法用于把字符串转换为小写。
return input.toLowerCase()