Angular 18 how to display injected file with ngx-extended-pdf-viewer

Angular 18 how to display injected file with ngx-extended-pdf-viewer
angular
Ethan Jackson

I'm currently stuck with the pdf view using ngx-extended-pdf-viewer (version 24.2.4). I'm currently using material dialogs and passing the file to it, from one dialog to another.

<div class="pt-3"> <button class="button-background w-100" mat-raised-button [disabled]="!selectedFile" (click)="onPreviewHandler()"> <mat-icon>search</mat-icon> <span>view</span> </button> </div> onPreviewHandler() { if (this.selectedFile) { this.dialog.open(PdfPreviewDialogComponent, { data: this!.selectedFile, height: "90vh", width: "80vw" }) } }

Once the PdfPreviewDialogCompionent is ready, the pdf file is not showed, but only the commands are visible. Here is the component with an example image.

<ngx-extended-pdf-viewer [src]="pdfSrc" useBrowserLocale="true" [height]="'auto'" [textLayer]="true" [showHandToolButton]="true" ></ngx-extended-pdf-viewer> export class PdfPreviewDialogComponent { pdfSrc: Blob; constructor(@Inject(MAT_DIALOG_DATA) public data: File) { const blob = new Blob([this.data], { type: "application/pdf" }); this.pdfSrc = blob; } }

viewer error

I'm not getting any error in the console or during the build. I also tried to download the generated blob and it is correctly downloaded.

Answer

I see you have passed the blob object to the ngx-extended-pdf-viewer. But it either accepts a url string, an array buffer or else a base64 string. Therefore try converting the blob object to a url string or a base64 string

export class PdfPreviewDialogComponent { pdfSrc: string; constructor(@Inject(MAT_DIALOG_DATA) public data: File) { const blob = new Blob([this.data], { type: "application/pdf" }); this.pdfSrc = URL.createObjectURL(blob); // try converting object url this.convertBlobToBase64(blob).then(base64 => { // if the above did not work use below this.pdfSrc = base64; }); } convertBlobToBase64(blob: Blob): Promise<string> { return new Promise((resolve, reject) => { const reader = new FileReader(); reader.onloadend = () => { resolve(reader.result as string); }; reader.onerror = reject; reader.readAsDataURL(blob); }); } }

Related Articles