axios通过pdf下载地址预览pdf

前言

最近做一个功能,根据一个pdf的下载地址,做出既能下载又能预览pdf的两个功能按钮,因为地址本身在浏览器中打开就能下载,直接记录怎么实现预览功能。

具体步骤

1.前台html代码

<iframe id="iframe" frameborder="0" style="width: 100%; height: 100%"></iframe>

2.前台js代码

axios({
  method: 'get',
  url:'/preview', 
  params:{
       pdfUrl:'https://xxxx/xxx/xxx.pdf'
  },
  responseType: 'blob',
}).then(function (response) {
  let blob = new Blob([response.data], { type: response.data.type })
  let url = URL.createObjectURL(blob)
  document.getElementById('iframe').src = url
}).catch(err => {
});

3.后台代码

 	@RequestMapping("/preview")
    public void preview(HttpServletResponse response, String pdfUrl) {
        response.setContentType("application/pdf");
        try(OutputStream out = response.getOutputStream();
            InputStream in = new BufferedInputStream(new URL(pdfUrl).openConnection().getInputStream())) {
            byte[] b = new byte[1024];
            int len = 0;
            while ((len = in.read(b))!=-1) {
                out.write(b,0,len);
            }
            out.flush();
        } catch (Exception e) {
            System.out.println(e);
        }
    }

后记

实现办法还有用pdf.js,因为不想在vue中添加依赖,没有采用。

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 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、付费专栏及课程。

余额充值