简体   繁体   English

如何在 vue.js 中使用 iframe 显示 pdf

[英]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.我有一个 vue.js webapp,我想在应用程序的 iframe 中显示一个 PDF,但它没有从assets文件夹中获取路径。 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方法:

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

But this did not work and gives following error:但这不起作用并出现以下错误:

Cannot GET /assets/my.pdf无法获取/assets/my.pdf

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

As I am using webpack, I also tried following, which also did not work:当我使用 webpack 时,我也尝试了以下操作,但这也不起作用:

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

This gives me following error:这给了我以下错误:

./src/assets/my.pdf ./src/assets/my.pdf

Module parse failed: >/Users/abc/work/codes/vue/src/assets/my.pdf Unexpected token (1:0)模块解析失败:>/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 .然而,上面的代码适用于图像,正如我之前在这里回答的那样。

1 template 1个模板

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

2 script 2 脚本

<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>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM