【问题标题】:Embed pdf in Angular2 component在Angular2组件中嵌入pdf
【发布时间】:2018-01-28 14:29:02
【问题描述】:

在 Angular 4.3 中,我想打开一个模式弹出窗口并显示一个嵌入的 pdf 文件,如下所示:https://pdfobject.com/static.html

我使用了弹出很好的modal popup component from this answer。我的模态测试 html 如下所示:

<a class="btn btn-default" (click)="setContent();modal.show()">Show</a>
<app-modal #modal>
  <div class="app-modal-header">
    Testing pdf embedding
  </div>
  <div class="app-modal-body">
    <div class="embed-responsive" *ngIf="ContentUrl">
      <object [attr.data]="ContentUrl"
              type="application/pdf"
              class="embed-responsive-item">
        <embed [attr.src]="ContentUrl"
               type="application/pdf" />
      </object>
    </div>
    <p><a [href]="ContentUrl">PDF Download</a></p>
  </div>
  <div class="app-modal-footer">
    <button type="button" class="btn btn-default" (click)="modal.hide()">Close</button>
  </div>
</app-modal>

在我的组件中,我这样设置ContentUrl

public ContentUrl: SafeUrl;
public setContent() {
    this.ContentUrl = this._sanitizer.bypassSecurityTrustResourceUrl("/img/test.pdf");
}

弹出窗口可以很好地打开,但它不显示嵌入的 pdf。它甚至不会尝试从服务加载 url。下载链接运行良好,并询问是否应将 pdf 保存到光盘或打开。
我也尝试将 pdf 嵌入弹出窗口之外,但也无济于事。
我试过 Chrome、Edge 和 IE。 None 显示嵌入的 pdf。

那么如何在角度组件中显示/嵌入 pdf?

【问题讨论】:

    标签: angular pdf


    【解决方案1】:

    我最终使用 innerHtml 创建了object

    在模板中:

    <div *ngIf="innerHtml"
      [innerHTML]="innerHtml">
    </div>
    

    在后面的代码中:

    public innerHtml: SafeHtml;
    public setInnerHtml(pdfurl: string) {
        this.innerHtml = this._sanitizer.bypassSecurityTrustHtml(
            "<object data='" + pdfurl + "' type='application/pdf' class='embed-responsive-item'>" +
            "Object " + pdfurl + " failed" +
            "</object>");
    }
    

    这样,对象在创建时就已经设置了它的数据属性。至少现在 PDF 像我想要的那样嵌入。

    【讨论】:

    • 如果我们知道我们注入的 html 没问题,是否可以绕过 sanitizer?
    • 爱国,我不明白你的问题和含义。
    • 我指的是您正在使用“this._sanitizer.bypassSecurityTrustHtml..”将对象 html 注入视图。所以我只是对通过消毒剂感到担心和好奇。
    • 啊,好的。 html 的每一部分都是由程序创建的,甚至是 pdfurl。没有用户输入用于创建 html。所以我认为没有理由清理 html。当然,如果在 html 中使用用户输入的数据,情况会有所不同。
    • 我仍然收到此错误Refused to display 'MYFULLLINK' in a frame because it set 'X-Frame-Options' to 'deny
    【解决方案2】:

    这段代码在 Angular 9 中为我工作

    import { DomSanitizer, SafeResourceUrl } from '@angular/platform-browser'
    
    public innerHtml: any;
    
    constructor(
    private domSanitizer: DomSanitizer
    ) { }
    
    const fileURL = URL.createObjectURL(result);
    
      this.innerHtml = this.domSanitizer.bypassSecurityTrustHtml(
        "<object data='" + fileURL + "' type='application/pdf' class='embed-responsive-item'>" +
        "Object " + fileURL + " failed" +
        "</object>");
    

    image

    【讨论】:

      猜你喜欢
      • 2016-10-30
      • 2016-03-01
      • 1970-01-01
      • 1970-01-01
      • 2016-07-03
      • 1970-01-01
      • 1970-01-01
      • 2017-01-26
      • 2012-04-30
      相关资源
      最近更新 更多