从服务器加载 pdf 并嵌入到 Vue 应用程序中 [英] Load pdf from server and embed in Vue app

查看:22
本文介绍了从服务器加载 pdf 并嵌入到 Vue 应用程序中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个返回 pdf 文件的 api.我试图在 vue.js 中显示它并找到了 vue-pdf 组件,它看起来应该可以完成这项工作.这是github上的项目

I have an api which returns a pdf file. I'm trying to display this in vue.js and found the vue-pdf component which looks like it should do the job. Here's the project on github

我能够调用 API 并获得二进制响应,但我无法将二进制数据转换为 vue-pdf 库可以显示的内容.

I'm able to call the API and get the binary response but I've not been able to convert the binary data into something which the vue-pdf library can display.

:src 属性的文档在这里

我的 vue 代码如下,其中一些失败的尝试被注释掉了.

My vue code is below with a few of the failed attempts commented out.

<template>
  <pdf :src="pdfsrc"></pdf>
</template>

<script>
import pdf from "vue-pdf";
import axios from "axios";

export default {
  components: {
    pdf
  },
  data() {
    return {
      pdfsrc: null
    };
  },
  created() {
    return axios
      .get(`${process.env.VUE_APP_API_INTRANET}/pdf`, {
        responseType: "application/pdf"
      })
      .then(response => {
        console.log("Success", response);
       
       // 1
       // this.pdfsrc = new Blob([response.data]);
       
       // 2
       //this.pdfsrc = response.data;
       
       //3
       //   for (var i = 0; i < response.data.length; ++i) {
        //   this.pdfsrc.push(response.data.charCodeAt(i) & 0xff);
        //   }

        //4
        this.pdfsrc = new Uint8Array(response.data);
      })
      .catch(console.error); //
  }
};
</script>

我意识到对于我的示例,我可以将 src 设置为 api 的 URL,但最终它需要添加授权标头并与 OAuth 调用链接,因此它需要是一个 api 调用.

I realise that for my example I could just set src to the URL of the api but ultimately it will need authorisation headers adding and chaining with OAuth calls so it needs to be an api call.

我还想将 pdf 与来自另一个 api 调用的一些数据并排显示,因此使用动态创建加载有数据和 .click() 的锚标记的技巧对我不起作用.

I also want to display the pdf side by side with some data from another api call so using the trick of dynamically creating an anchor tag loaded with the data and .click() 'ing it won't work for me.

推荐答案

首先将您预期的 responseType 更改为blob":

First change your expected responseType to "blob":

return axios.get(`${process.env.VUE_APP_API_INTRANET}/pdf`, {
  responseType: "blob"
})

还将二进制响应转换为 Blob,然后生成一个对象网址:

Also convert the binary response to a Blob and then generate an object url:

.then(response => {
  console.log("Success", response);
  const blob = new Blob([response.data]);
  const objectUrl = URL.createObjectURL(blob);
  this.pdfsrc = objectUrl;
})

不要忘记使用 revokeObjectURL 完成后避免内存泄漏.

Don't forget to use revokeObjectURL when finished with it to avoid memory leaks.

这篇关于从服务器加载 pdf 并嵌入到 Vue 应用程序中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆