0

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.

Community
  • 1
  • 1
Saurabh
  • 71,488
  • 40
  • 181
  • 244
  • What happened when you were returning `'../../assets/my.pdf'` string? – Amresh Venugopal Apr 03 '17 at 13:31
  • @SLYcee No, I think "()" is needed – Saurabh Apr 03 '17 at 13:38
  • @AmreshVenugopal I have added the error in the question. – Saurabh Apr 03 '17 at 13:38
  • So you return `'../../assets/my.pdf'` but the error says `'/assets/my.pdf'`? Also, is the result same if you do {{ getPDFPath() }} just above the ` – Amresh Venugopal Apr 03 '17 at 13:42
  • Do you want a simple reference to the pdf ? is it available via http directly? Can you use an absolute path? – Frnak Apr 03 '17 at 13:46
  • I want to just show it in an iframe as part of the page, I have a copy of it, which I am putting in assets folder. I can serve images from this path. – Saurabh Apr 03 '17 at 13:48
  • Images and css could have been handled by webpack loaders. Not sure but because in the error the path is different so my guess is to try some other file like a docx or csv? If you can check the `__dirname` of the file in which you have the iframe? – Amresh Venugopal Apr 03 '17 at 14:36

1 Answers1

1

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>
Jesus Leon
  • 101
  • 1
  • 3