Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Load pdf from server and embed in Vue app

Tags:

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

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.

The documentation for the :src prop is here

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>

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.

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.

like image 431
Twisted Avatar asked Dec 11 '20 17:12

Twisted


People also ask

How do I open a PDF in HTML?

The quickest way to convert your PDF is to open it in Acrobat. Go to the File menu, navigate down to Export To, and select HTML Web Page. Your PDF will automatically convert and open in your default web browser.


1 Answers

First change your expected responseType to "blob":

return axios.get(`${process.env.VUE_APP_API_INTRANET}/pdf`, {
  responseType: "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;
})

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

like image 176
Dan Avatar answered Sep 30 '22 15:09

Dan