Saurabh
Saurabh

Reputation: 73609

How to show pdf with iframe in vue.js

I have a vue.js webapp, I want to show an PDF in an iframe in the app, but it is not taking the path from the assets folder. Here is my code:

<iframe :src="getPDFPath()" style="width: 100vw;height: 100%;border: none;">
  Oops! an error has occurred.
</iframe>

Here is the getPDFPath method:

getPDFPath () {
   return '../../assets/my.pdf'
}

But this did not work and gives following error:

Cannot GET /assets/my.pdf

However result of {{ getPDFPath() }} is : ../../assets/my.pdf.

As I am using webpack, I also tried following, which also did not work:

getPDFPath () {
  var files = require.context('../../assets/', false)
  return files('./my.pdf')
}

This gives me following error:

./src/assets/my.pdf

Module parse failed: >/Users/abc/work/codes/vue/src/assets/my.pdf Unexpected token (1:0)

You may need an appropriate loader to handle this file type.

However above code works for images, as I have earlier answered here.

Upvotes: 1

Views: 10014

Answers (1)

Jesus Leon
Jesus Leon

Reputation: 121

1 template

<iframe :src="pdfsrc" style="width: 100%;height: 300px; border: none;">
Oops! an error has occurred.
</iframe>

2 script

<script>
export default {
  data: () => ({
    pdfsrc: null
  }),
  methods: {
    getPDFPath () {
      return axios
      .get('/sample-3pp.pdf', {
        responseType: "blob"
      })
      .then(response => {
        console.log("Success", response);
        const blob = new Blob([response.data]);
        const objectUrl = URL.createObjectURL(blob);
        this.pdfsrc = objectUrl;
      })
     .catch(console.error); //
    } 
    created() {
        this.getPDFPath();
    }
}
</script>

Upvotes: 3

Related Questions