【问题标题】:How to show pdf with iframe in vue.js如何在 vue.js 中使用 iframe 显示 pdf
【发布时间】:2017-04-03 13:29:08
【问题描述】:

我有一个 vue.js 网络应用程序,我想在应用程序的 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/assets/my.pdf

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

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

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

【问题讨论】:

  • 返回'../../assets/my.pdf'字符串时发生了什么?
  • @SLYcee 不,我认为需要“()”
  • @AmreshVenugopal 我在问题中添加了错误。
  • 所以你返回'../../assets/my.pdf' 但错误显示'/assets/my.pdf'?此外,如果您在 &lt;iframe&gt; 上方执行 {{ getPDFPath() }},结果是否相同?
  • 你想要一个简单的 pdf 参考吗?可以直接通过http获得吗?可以用绝对路径吗?

标签: javascript pdf iframe vue.js vuejs2


【解决方案1】:

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>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-02-03
    • 2017-05-29
    • 2012-03-31
    • 2017-11-13
    • 1970-01-01
    • 2019-04-18
    • 2020-09-28
    • 1970-01-01
    相关资源
    最近更新 更多