Articles in this section
Category / Section

How to Load a Document Using a Base64 String in Angular PDF Viewer?

5 mins read
Description:

This article explains how to load a document using a Base64 string as the documentPath in the Syncfusion Angular PDF Viewer component within an Angular application. By following this guide, users will be able to load a PDF document after fetching the Base64 string asynchronously from a service, ensuring that the viewer waits until the data is available.

Solution:

To load a document using a Base64 string in Angular, you can use the Syncfusion PDF Viewer component. The PDF Viewer requires the documentPath to load the document, and in this case, we’ll set it to the Base64 string of the PDF. In the ngOnInit method, we fetch the Base64 string from a service asynchronously, and once the Base64 string is retrieved, the PDF Viewer will render the document.

Prerequisites:

Before proceeding with the implementation, ensure that the following steps are completed:

  1. Syncfusion PDF Viewer Setup: Make sure the Syncfusion PDF Viewer is installed and set up in your Angular project. Follow the Getting Started with Syncfusion PDF Viewer for Angular guide if you haven’t already.
  2. Basic Knowledge of Angular: Familiarity with Angular components and lifecycle hooks, especially ngOnInit, will help you follow along with the implementation.
Code Snippets
Install and Configure Syncfusion PDF Viewer

First, install the necessary Syncfusion PDF Viewer modules and services in your Angular project and import them as needed.

import { Component, OnInit } from '@angular/core';
import { PdfViewerModule, LinkAnnotationService, BookmarkViewService,
         MagnificationService, ThumbnailViewService, ToolbarService,
         NavigationService, TextSearchService, TextSelectionService,
         PrintService, FormDesignerService, FormFieldsService, 
         AnnotationService, PageOrganizerService } from '@syncfusion/ej2-angular-pdfviewer';
         import { HttpClient } from '@angular/common/http';
Create the PDF Viewer Component

In your component’s HTML file, set up the PDF Viewer element to display the PDF document:

@Component({
  selector: 'app-root',
  template: `<div class="content-wrapper">
              <!-- Conditionally render the PDF Viewer or a Loading message -->
              <ng-container *ngIf="isPdfLoaded; else loading">
                <ejs-pdfviewer id="pdfViewer"
                    [resourceUrl]='resource'
                    [documentPath]="base64String" 
                    style="height:1040px;display:block" >
                </ejs-pdfviewer>
              </ng-container>
              <ng-template #loading>
                <p>Loading PDF...</p>
              </ng-template>
             </div>`,
  providers: [ LinkAnnotationService, BookmarkViewService, MagnificationService,
               ThumbnailViewService, ToolbarService, NavigationService,
               TextSearchService, TextSelectionService, PrintService,
               AnnotationService, FormDesignerService, FormFieldsService, PageOrganizerService]
})
Fetch the Base64 String and Load the PDF Document

In your component’s TypeScript file, use ngOnInit to fetch the Base64 string asynchronously and load the PDF. This will ensure that the PDF Viewer only loads the document once the Base64 string is available.

export class AppComponent implements OnInit {
  public resource: string = "http://localhost:4200/assets/ej2-pdfviewer-lib";
  base64String: string = ''; 
  isPdfLoaded: boolean = false; 

  constructor(private http: HttpClient) {}
  
  async ngOnInit() {
    await this.fetchBase64FromURL(
      'https://cdn.syncfusion.com/content/pdf/pdf-succinctly.pdf'
    );
  }

  async fetchBase64FromURL(url: string) {
    const requestBody = {
      data: url
    };

    this.http.post('https://localhost:7237/pdfviewer/LoadPdf', requestBody)
      .subscribe((response: any) => {
        this.base64String = response.base64String as string; // Store Base64 string
        this.isPdfLoaded = true; // Mark PDF as loaded
      }, error => {
        console.error('Error loading document', error);
      });
  }
}
Key Features Used in the Code:
  1. Base64 String as documentPath: The documentPath property is set to the Base64 string retrieved from the service, ensuring the PDF document is displayed from the Base64-encoded data.
  2. Conditional Rendering: The ngIf directive is used to display the PDF Viewer once the Base64 string is fetched. Until the Base64 string is loaded, a “Loading PDF…” message is displayed.
  3. ngOnInit: This lifecycle hook ensures that the PDF Viewer waits until the Base64 string is fetched from the service before rendering the document.
Sample:

You can find the full sample in our GitHub repository.

Conclusion
I hope you enjoyed learning how to load a document using a base64 string in Angular PDF Viewer.

You can refer to Angular PDF Viewer feature tour page to know about its other groundbreaking feature representations and documentation, and how to quickly get started for configuration specifications. You can also explore our Angular PDF Viewer example to understand how to create and manipulate data.

For current customers, you can check out our components from the License and Downloads page. If you are new to Syncfusion, you can try our 30-day free trial to check out our other controls.

If you have any queries or require clarifications, please let us know in the comments section below. You can also contact us through our support forums, Direct-Trac, or feedback portal. We are always happy to assist you!

Did you find this information helpful?
Yes
No
Help us improve this page
Please provide feedback or comments
Comments (0)
Please  to leave a comment
Access denied
Access denied