Base64 to PDF in Angular
In modern web applications built with Angular, you often receive PDF content as a Base64 encoded string from a REST API. To allow users to view or download this content, you need to decode it on the client side.
Angular/TypeScript Example
Here is a TypeScript function you can include in your Angular component to handle the conversion and trigger a download.
pdf-utils.ts
/**
* Decodes a Base64 string and triggers a PDF download in the browser.
* @param base64String The Base64 encoded string (with or without data prefix)
* @param fileName The desired name for the downloaded file
*/
export function downloadPdf(base64String: string, fileName: string = 'document.pdf') {
// 1. Remove data URL prefix if it exists
const cleanBase64 = base64String.replace(/^data:application\/pdf;base64,/, '');
// 2. Convert Base64 string to a binary string
const byteCharacters = atob(cleanBase64);
// 3. Create an array of byte values
const byteNumbers = new Array(byteCharacters.length);
for (let i = 0; i < byteCharacters.length; i++) {
byteNumbers[i] = byteCharacters.charCodeAt(i);
}
// 4. Create a Uint8Array from the byte values
const byteArray = new Uint8Array(byteNumbers);
// 5. Create a Blob from the Uint8Array
const blob = new Blob([byteArray], { type: 'application/pdf' });
// 6. Create a link element and trigger the download
const url = window.URL.createObjectURL(blob);
const link = document.createElement('a');
link.href = url;
link.download = fileName;
// Append to body, click, and remove
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
// Clean up the URL object
window.URL.revokeObjectURL(url);
} Implementation Steps
- atob(): This built-in JavaScript function decodes a string of data which has been encoded using Base64 encoding.
- Uint8Array: We transform the decoded string into a typed array of 8-bit unsigned integers, which is the format required for creating a Blob.
- Blob Object: The
Blobconstructor creates a file-like object of immutable, raw data. We specifyapplication/pdfas the MIME type. - Object URL:
URL.createObjectURL()creates a temporary URL that points to the data in memory. - Anchor Tag: We programmatically create an
<a>tag with adownloadattribute to force the browser to download the file instead of navigating to it.
Best Practices
When working with large PDF files in Angular, consider using a library like FileSaver.js for better cross-browser compatibility. Additionally, always remember to revoke the Object URL to prevent memory leaks in your single-page application.
Try our online converter
Don't want to write code? Use our free tool to convert your Base64 strings to PDF instantly.
Base64 to PDF Online