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

时间:2017-04-03 13:29:08

标签: javascript pdf iframe vue.js vuejs2

我有一个vue.js webapp,我想在应用程序的iframe中显示PDF,但它没有从assets文件夹中获取路径。这是我的代码:

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

以下是getPDFPath方法:

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

但这不起作用,并给出以下错误:

  

无法获取/assets/my.pdf

{{ getPDFPath() }}的结果为:../../assets/my.pdf

当我使用webpack时,我也尝试了以下操作,但也没有用:

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

这给了我以下错误:

  

./ SRC /资产/ my.pdf

     

模块解析失败:&gt; /Users/abc/work/codes/vue/src/assets/my.pdf   意外的令牌(1:0)

     

您可能需要适当的加载程序来处理此文件类型。

然而,上面的代码适用于图像,正如我之前回答here

1 个答案:

答案 0 :(得分:0)

1 个模板

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

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>