【问题标题】:Angular 8 - how to dynamically set iframe src to a pdfAngular 8 - 如何将 iframe src 动态设置为 pdf
【发布时间】:2020-06-18 19:33:22
【问题描述】:

在我的 Angular 8 项目的一个组件中,我有这个方法,它非常适合在新选项卡中打开 PDF 报告:

public getReport() {
    if (this.userForm.valid) {
      this.applyFormData();
      // open before ajax call to pass browser security
      let windowRef = window.open('about:blank', '_blank');
      this._dataSvc.getDocument("LaborLevel/GetReport", this.reportParmsDto, (pdfFile: Blob) => {
        if (pdfFile) {
          let fileURL = URL.createObjectURL(pdfFile);
          windowRef.location.href = fileURL;
        } else {
          windowRef.close();
        }
      });
    }
  }

但是,我想在控件中托管的 iframe 中显示相同的文档,而不是打开一个新选项卡。因此,我在组件中定义了一个 iframe,如下所示:

<iframe id="iframe" #iframe width="400" height="500" [src]="dataLocalUrl" type="application/pdf" *ngIf="dataLocalUrl"></iframe>

我创建了这个方法来将 iframe 的内容设置为 PDF 文档:

public getReport() {
    if (this.userForm.valid) {
      this.applyFormData();
      this._dataSvc.getDocument("LaborLevel/GetReport", this.reportParmsDto, (pdfFile: Blob) => {
        if (pdfFile) {
           let objUrl = URL.createObjectURL(pdfFile);
           this.dataLocalUrl = this._sanitizer.bypassSecurityTrustResourceUrl(objUrl);
        } 
      });
    }
  } 

但是,当我这样做时,iframe 中根本没有显示任何内容。我没有收到任何类型的错误消息, 但它只是空的(全白)。

我查看了一些文章,这些文章表明我正在做的事情应该有效(包括 Angular 2 how to display .pdf file),但它不起作用。

注意:如果我对某个网站的 URL 进行硬编码,例如:

this.dataLocalUrl = this._sanitizer.bypassSecurityTrustResourceUrl("https://theuselessweb.com/");

它工作正常。

如果我将 objUrl ("blob:https://localhost:44303/1e820772-0df8-44c0-9416-96f560a8fc74") 粘贴到浏览器新选​​项卡的位置栏中,则报告显示得很好。

为什么我的 blob 不能在 iframe 中工作???

感谢您的帮助!

【问题讨论】:

  • 您的项目中有文档吗?还是您下载并显示它? .

标签: angular iframe


【解决方案1】:

我以前遇到过这个问题。在您的情况下, dataLocalUrl 在您加载 iframe 时存在(即使没有内容)。在我的案例中,我所做的是在将 URL 分配给变量(在您的案例中为 dataLocalUrl)后强制 iframe 刷新其内容,它对我来说非常有效。我会尝试找到项目并为您粘贴代码。

【讨论】:

  • 你能把代码贴出来吗?
猜你喜欢
  • 1970-01-01
  • 2017-03-26
  • 2010-11-05
  • 2014-05-16
  • 2013-06-03
  • 2015-06-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多