vue项目导出图片至word方法。

实现以下两点功能:
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()
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值