In this article, we take a look at how Base64 works in Angular. We will show you how to encode and decode text and PDF files using Angular. We will also show you how to use two packages: ng2-pdf-viewer
and ng2-pdfjs-viewer
.
What is Base64?
Base64 is an ASCII-based binary-to-text encoding technique used in computer systems to represent binary data such as images or files. It translates binary data into a string representation suitable for transmission via text-based protocols. Each set of three bytes of input data is represented by four ASCII characters, allowing binary data to be safely exchanged in environments where only text is permitted.
What is Angular?
Google’s Angular is a popular JavaScript framework for creating dynamic web applications. It offers capabilities such as data binding, dependency injection, and modular components in a structured framework for developing single-page applications. Angular‘s broad ecosystem and tools make it easier to create complex and engaging user experiences.
Base64 Encoding and Decoding in Angular
Base64 encoding and decoding are critical techniques for converting binary data to a text-based format that may be used for a variety of communication and storage reasons. These operations are possible in Angular by utilizing the built-in JavaScript functions and libraries.
In Angular, you can perform Base64 encoding using the btoa()
function, which stands for “binary to ASCII.” This function takes binary data as input and returns a Base64-encoded string. For example, to encode a string, you can call the btoa()
function with the string as an argument:
const originalString = 'B64Encode.com'; const encodedString = btoa(originalString); console.log(encodedString);
To decode a Base64-encoded string back to its original binary form, you can use the atob()
function, which stands for “ASCII to binary.” This function takes a Base64-encoded string as input and returns the original binary data. Here’s an example:
const encodedString = "QjY0RW5jb2RlLmNvbQ=="; const decodedString = atob(encodedString); console.log(decodedString);
Example: PDF to Base64 in Angular
In this example, we create an Angular component named PdfToBase64Component
. The component includes an input element for selecting a PDF file and a button to trigger the conversion process. When a file is selected, the handleFileInput()
function is called, which reads the file and converts it to a Base64-encoded string using a FileReader. The Base64-encoded string is then displayed in a textarea element.
import { Component } from '@angular/core'; import { HttpClient } from '@angular/common/http'; @Component({ selector: 'app-pdf-to-base64', template: ` <input type="file" (change)="handleFileInput($event)" accept=".pdf" /> <button (click)="convertToBase64()">Convert to Base64</button> <div *ngIf="base64String"> <h3>Base64-encoded PDF content:</h3> <textarea rows="10">{{ base64String }}</textarea> </div> `, }) export class PdfToBase64Component { base64String: string | null = null; constructor(private http: HttpClient) {} handleFileInput(event: any): void { const file = event.target.files[0]; if (file) { this.convertFileToBase64(file); } } convertFileToBase64(file: File): void { const reader = new FileReader(); reader.onload = (event: any) => { this.base64String = event.target.result.split(',')[1]; }; reader.readAsDataURL(file); } convertToBase64(): void { // Perform additional operations if needed } }
Example: Base64 to PDF in Angular
In this component, the user enters the Base64-encoded PDF content in a textarea. When the “Convert to PDF” button is clicked, the convertToPdf()
method is called. This method decodes the Base64 content using the atob()
function and creates a Uint8Array
from the decoded binary data.
import { Component } from '@angular/core'; @Component({ selector: 'app-base64-to-pdf', template: ` <textarea placeholder="Enter Base64-encoded PDF content" [(ngModel)]="base64Content" rows="10" ></textarea> <button (click)="convertToPdf()">Convert to PDF</button> <div *ngIf="pdfBlobUrl"> <h3>Converted PDF:</h3> <object [data]="pdfBlobUrl" type="application/pdf" width="100%" height="500px"> Your browser does not support PDF embedding. </object> </div> `, }) export class Base64ToPdfComponent { base64Content: string = ''; pdfBlobUrl: string | null = null; convertToPdf(): void { if (this.base64Content) { const binaryData = atob(this.base64Content); const byteArray = new Uint8Array(binaryData.length); for (let i = 0; i < binaryData.length; i++) { byteArray[i] = binaryData.charCodeAt(i); } const blob = new Blob([byteArray], { type: 'application/pdf' }); this.pdfBlobUrl = URL.createObjectURL(blob); } } }
Angular PDF Base64 Viewer: ng2-pdf-viewer
Here’s an example of an Angular PDF viewer that uses ng2-pdf-viewer to display a PDF file from a Base64-encoded string:
npm install ng2-pdf-viewer
Create a new component named PdfViewerComponent
:
import { Component, Input } from '@angular/core'; @Component({ selector: 'app-pdf-viewer', template: ` <div *ngIf="pdfSrc"> <pdf-viewer [src]="pdfSrc" [render-text]="true" style="display: block;"></pdf-viewer> </div> `, }) export class PdfViewerComponent { @Input() pdfSrc: string | undefined; }
Use the PdfViewerComponent
in your main application component (AppComponent
):
import { Component } from '@angular/core'; @Component({ selector: 'app-root', template: ` <h1>Angular PDF Viewer Base64 Example</h1> <app-pdf-viewer [pdfSrc]="base64Pdf"></app-pdf-viewer> `, }) export class AppComponent { base64Pdf = '...'; // Replace with your Base64-encoded PDF content }
In the above example, the PdfViewerComponent
takes an input property pdfSrc
, which should be the Base64-encoded PDF content. The ng2-pdf-viewer
package handles rendering the PDF using the provided Base64 data.
Remember to include the PdfViewerModule
in your AppModule
:
import { NgModule } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import { PdfViewerModule } from 'ng2-pdf-viewer'; // Import PdfViewerModule import { PdfViewerComponent } from './pdf-viewer.component'; // Import PdfViewerComponent import { AppComponent } from './app.component'; @NgModule({ imports: [ BrowserModule, PdfViewerModule, // Add PdfViewerModule ], declarations: [ AppComponent, PdfViewerComponent, // Add PdfViewerComponent ], bootstrap: [AppComponent] }) export class AppModule { }
Replace '...'
in the base64Pdf
property of the AppComponent
with your actual Base64-encoded PDF content.
Angular PDF Base64 Viewer: ng2-pdfjs-viewer
Here’s how you can create an Angular PDF Base64 Viewer using the ng2-pdfjs-viewer
package.
First, install the ng2-pdfjs-viewer
package by running the following command:
npm install ng2-pdfjs-viewer
Create a new component named PdfBase64ViewerComponent
:
import { Component, Input } from '@angular/core'; @Component({ selector: 'app-pdf-base64-viewer', template: ` <div *ngIf="pdfSrc"> <ng2-pdfjs-viewer [pdfSrc]="pdfSrc" [show-all]="true"></ng2-pdfjs-viewer> </div> `, }) export class PdfBase64ViewerComponent { @Input() pdfSrc: string | undefined; }
Use the PdfBase64ViewerComponent
in your main application component (AppComponent
):
import { Component } from '@angular/core'; @Component({ selector: 'app-root', template: ` <h1>Angular PDF Base64 Viewer: ng2-pdfjs-viewer Example</h1> <app-pdf-base64-viewer [pdfSrc]="base64Pdf"></app-pdf-base64-viewer> `, }) export class AppComponent { base64Pdf = '...'; // Replace with your Base64-encoded PDF content }
Include the PdfJsViewerModule
in your AppModule
:
import { NgModule } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import { PdfJsViewerModule } from 'ng2-pdfjs-viewer'; // Import PdfJsViewerModule import { PdfBase64ViewerComponent } from './pdf-base64-viewer.component'; // Import PdfBase64ViewerComponent import { AppComponent } from './app.component'; @NgModule({ imports: [ BrowserModule, PdfJsViewerModule, // Add PdfJsViewerModule ], declarations: [ AppComponent, PdfBase64ViewerComponent, // Add PdfBase64ViewerComponent ], bootstrap: [AppComponent] }) export class AppModule { }
Replace '...'
in the base64Pdf
property of the AppComponent
with your actual Base64-encoded PDF content.
How to Open Base64 PDF in New Tab
This code shows how to open a decoded Base64 PDF in a new tab/window.
openPdfInNewTab(): void { if (this.base64Pdf) { const byteCharacters = atob(this.base64Pdf); const byteNumbers = new Array(byteCharacters.length); for (let i = 0; i < byteCharacters.length; i++) { byteNumbers[i] = byteCharacters.charCodeAt(i); } const byteArray = new Uint8Array(byteNumbers); const blob = new Blob([byteArray], { type: 'application/pdf' }); const blobUrl = URL.createObjectURL(blob); window.open(blobUrl, '_blank'); // This opens the new tab } }
The line window.open(blobUrl, '_blank')
opens a new tab with the Blob URL representing the Base64-encoded PDF content. The '_blank'
parameter indicates to the window.open()
function to open the provided URL in a new tab.