vue实现pdf下载

接口代码:

export function getDownloadAPI(url) {
  return request({
    url: url,
    responseType: 'blob',
    method: 'GET'
  })
}

注意,以上代码因为pdf的下载地址后台已经返回,所以这里的url需要用传参的方式!!

html代码:

 <el-button @click="hrefClick" type="success" >下载</el-button>

js代码:

 // pdf下载
      hrefClick(){
        getDownloadAPI(this.formInline.invoice_url).then(res => {
          if(res.size > 0){
            const content = res
            const blob = new Blob([content])
            const fileName = '发票.pdf'
            if ('download' in document.createElement('a')) { // 非IE下载
              const elink = document.createElement('a')
              elink.download = fileName
              elink.style.display = 'none'
              elink.href = URL.createObjectURL(blob)
              document.body.appendChild(elink)
              elink.click()
              URL.revokeObjectURL(elink.href) // 释放URL 对象
              document.body.removeChild(elink)
            } else { // IE10+下载
              navigator.msSaveBlob(blob, fileName)
            }
            /* this.$message.success("导出成功")*/
          }
        })
      },

 

  • 1
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
实现这个功能,我们需要用到以下两个库: 1. `pdfjs-dist`:用于解析 PDF 文件并将其转换为可供浏览器渲染的 HTML。 2. `vue-pdf`:一个 Vue 组件,用于在页面上呈现 PDF 文件。 下面是具体的实现步骤: 1. 安装依赖: ``` npm install pdfjs-dist vue-pdf --save ``` 2. 在 Vue 组件中引入所需的库: ```javascript import pdfjsLib from 'pdfjs-dist/webpack'; import VuePdf from 'vue-pdf'; ``` 3. 定义一个方法,用于下载 PDF 文件: ```javascript downloadPdf() { const url = 'your_pdf_url'; axios.get(url, { responseType: 'blob' }).then(response => { const blob = new Blob([response.data], { type: 'application/pdf' }); const url = window.URL.createObjectURL(blob); const link = document.createElement('a'); link.href = url; link.download = 'your_pdf_name'; link.click(); }); } ``` 4. 在组件中使用 `vue-pdf` 组件: ```html <template> <div> <button @click="downloadPdf">下载 PDF</button> <vue-pdf :src="pdfSrc" :show-toolbar="true"></vue-pdf> </div> </template> <script> import pdfjsLib from 'pdfjs-dist/webpack'; import VuePdf from 'vue-pdf'; export default { components: { VuePdf }, data() { return { pdfSrc: '' }; }, methods: { downloadPdf() { // 下载 PDF 文件的代码 } }, mounted() { const url = 'your_pdf_url'; pdfjsLib.getDocument(url).promise.then(pdf => { this.pdfSrc = pdf; }); } }; </script> ``` 这样,当用户点击下载按钮时,会下载 PDF 文件并以弹窗的形式呈现在页面上。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值