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?
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With