Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Embed pdf in Angular2 component

Tags:

angular

pdf

In angular 4.3 I want to open a modal popup and show an embedded pdf file, like shown here: https://pdfobject.com/static.html

I used the modal popup component from this answer which pops up nicely. My test html for the modal looks like this:

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

In my component I set ContentUrl like this:

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

The popup opens nicely, but it does not show the embedded pdf. It does not even try to load the url from the service. The download link works nicely and asks if the pdf should be saved to disc or opened.
I tried to embed the pdf outside of the popup to no avail, too.
I tried Chrome, Edge and IE. None displays the embedded pdf.

So how do I show/embed a pdf in an angular component?

like image 958
Sam Avatar asked Aug 20 '17 11:08

Sam


2 Answers

I ended up creating the object using innerHtml.

In the template:

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

In the code behind:

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>");
}

This way the object already has it's data attribute set upon creation. At least now the PDF is embedded like I wanted to.

like image 85
Sam Avatar answered Oct 22 '22 14:10

Sam


this code worked for me in 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

like image 1
danish ali Avatar answered Oct 22 '22 13:10

danish ali