vue pdf下載

周家大小姐.發表於2020-10-14
 <el-table-column label="保單號" show-overflow-tooltip min-width="220">
              <template slot-scope="scope">
                <span>{{ scope.row.policyNoCI }}</span>
                <span v-if="scope.row.policyNoCI" :key="scope.row.policyNoCI" class="link-type" @click="download(scope.row.policyNoCI)">下載</span>
              </template>
            </el-table-column>

 js檔案方法

 import { ePolicyFileDownloadMixin } from '@/views/tool/policy-download/mixin/e-policy-file-download-mixin'
export default {
    name: 'HistoryProposal',
    mixins: [ ePolicyFileDownloadMixin],
 methods: {
  download(VISACODE) {
        const params = {
          KEY: 'getEpolicyFile',
          VISACODE,
          CALL_SYSTEM: 'xsqt',
          TYPE: 'E',
          FILE_TYPE: 'PDF'
        }
        this.getEPolicyFile(params, `${params.VISACODE}.pdf`, 'application/pdf')
      },
}

}

e-policy-file-download-mixin.js

import { base64String2FileAndSave } from '@/utils'
 // 電子保單下載
    getEPolicyFile(params, fileName, fileType) {
      this.downloading = true
      const _params = { data: { root: { EDI: { ...params } } } }
      getepolicyfile(_params)
        .then(data => {
          const base64String = data['return.pdf']
          try {
            const content = window.atob(base64String)
            JSON.parse(content)
            this.$message.error('電子保單不存在')
          } catch (e) {
            base64String2FileAndSave(base64String, fileName, fileType)
          }
          this.downloading = false
        })
        .catch(e => {
          this.downloading = false
          this.$message.error(e.toString())
        })
    }

utils.js中的base64String2FileAndSave方法

import { saveAs } from 'file-saver'//外掛
/**
 * base64轉檔案並儲存
 * @param str
 * @param fileName
 * @param fileType
 */
export function base64String2FileAndSave(str, fileName, fileType) {
  const s = window.atob(str)
  const buf = new ArrayBuffer(s.length)
  const view = new Uint8Array(buf)
  for (let i = 0; i !== s.length; ++i) {
    view[i] = s.charCodeAt(i) & 0xFF
  }
  saveAs(new Blob([buf], { type: fileType }), fileName)
}

 

相關文章