You can use HttpClient to get the file from url. First you have to import HttpClientModule in app.module.ts

import { HttpClientModule } from '@angular/common/http';
imports: [...,
     'HttpClientModule',
       ...]

After that import in your component.ts HttpClient from '@angular/common/http' and add the instance in the constructor.

constructor(private http: HttpClient) { }

add the method

convertToBase64(url: string) {
    this.http.get(url, { responseType: "blob" }).subscribe(blob => {
      const reader = new FileReader();
      const binaryString = reader.readAsDataURL(blob);
      reader.onload = (event: any) => {
        //Here you can do whatever you want with the base64 String
        console.log("File in Base64: ", event.target.result);
      };

      reader.onerror = (event: any) => {
        console.log("File could not be read: " + event.target.error.code);
      };
    });
}
Answer from Oscar Ernesto Gonzalez on Stack Overflow
🌐
Syncfusion
help.syncfusion.com › documentation › document processing › pdf › pdf viewer › angular › how to › get base64
How to Get the Base64 Value of a PDF in Angular PDF | Syncfusion
Now - import { Component, OnInit } from '@angular/core'; import { LinkAnnotationService, BookmarkViewService, MagnificationService, ThumbnailViewService, ToolbarService, NavigationService, AnnotationService, TextSearchService, TextSelectionService, FormFieldsService, FormDesignerService, PrintService } from '@syncfusion/ej2-angular-pdfviewer'; @Component({ selector: 'app-root', template: ` <div class="content-wrapper"> <button (click)="getBase64()" style="margin-bottom: 20px;">Get Base64</button> <ejs-pdfviewer id="pdfViewer" [documentPath]='document' [serviceUrl]='service' style="height: 640px; dis
Discussions

typescript - Angular 6 - Unable to Convert Base64 to PDF - Stack Overflow
I'm working on Angular 6. Hence, I un-commented all the entries in pollyfills.ts. Yet, it doesn't work. 2018-09-04T19:07:18.59Z+00:00 ... How could i make this pdf viewable on my UI template as a section, as in on click of a button the pdf is generated and then made viewable 2019-04-17T10:45:59.343Z+00:00 ... Save this answer. ... Show activity on this post. Your problem is that you are not decoding your base 64 PDF, use the function atob() to ... More on stackoverflow.com
🌐 stackoverflow.com
August 24, 2018
typescript - convert PDF file using path to Base64 String in Javascript - Stack Overflow
Leo's answer will result in Uncaught TypeError: Failed to construct 'File': The provided value cannot be converted to a sequence. as xRdev said ... creates a new empty file with just content "foo" inside it, simulating that it is stored in path "/pdf/test.pdf" so eventhough you get base64 it doesnt ... More on stackoverflow.com
🌐 stackoverflow.com
September 19, 2018
angularjs - Unable to convert PDF returned response to base64 in JavaScript - Stack Overflow
Below is the PDF response is coming from the API server and I tried to convert to a PDF file but I couldn't. %PDF-1.3 %ÿÿÿÿ 4 0 obj More on stackoverflow.com
🌐 stackoverflow.com
Is it a good idea to convert images into base64 string and save them in database?
You will get many people saying don't because if not implemented well it can bite ya. Don't be concerned about "optimal", tell yourself "good enough" and "don't let perfect be the enemy of good". But I have done this for several projects (enterprise, mission critical systems) and it works just fine. From the developer standpoint I love it. When I yank the "byte array" from the DB I can just pass it right to the client as-is, just adding on the mime type, super simple. Right now I have a system that stores photos of students at a university and we serve those out with an API. All done in C# and SQL Server. We have probably 50,000 photos and it is lighting fast. That being said I have also stored files in S3 and just stored the name in the DB. I will usually rename the file so S3 stores it efficiently. I like things like s3 better than a file system since you can dedicate a bucket just to this and some sysadmin won't go mucking around. I agree with you on storing the unstructured binary data along with your structured data for simplicity. I had a project once that wrote images to a filesystem. Years later older images were lost due to some file system cleanup process. Over my 25 years programming I have found you cannot guess where the issues will be. Don't optimize until you measure it. If you can build a proof of concept then hammer it, do it. Write a script that inserts and reads images and loop it for a few hours. See what happens. Also if you implement something and a few years later it starts to falter, then refactor. But you need to monitor! This is another place where people get bit, they do something like this and just let it run in a corner until it "just dies for no reason" one day. You or someone needs to care and feed for it. I am going to assume on-prem Microsoft SQL Server, your usage may vary. Use "VARBINARY(MAX)" for the field type https://docs.microsoft.com/en-us/sql/t-sql/data-types/binary-and-varbinary-transact-sql?view=sql-server-ver15 Put it in a table by itself with an id to look it up. Store filename, and filetype(mime-type) too if needed. Slap an index on the id, reference that id in other tables. Critical: Put the table in its own filegroup separate from the other tables. This will allow for faster restores since you can restore the primary filegroup and get your DB back online ASAP, then as it is up and running restore the filegroup with the images. So instead of the whole DB being down for hours, it is up in minutes with only the images being unavailable for hours. https://docs.microsoft.com/en-us/sql/relational-databases/databases/database-files-and-filegroups?view=sql-server-ver15 As with all DBs the filegroups should not be on the system (C) drive, maybe even put the images table filegroup on its own drive with nothing else. Do set a limit on the incoming filesize in your code. Someone could send in a few Blu-ray ISOs and cripple your system. In .NET code you store the image data in a byte array "byte[] " variable. That byte array is what is stored in the varbinary(max) DB field. It is easy to convert the incoming image/file to byte[], just google around for that there are many easy to do it. Design and implement a cleanup process and purge old unneeded records. No one ever seems to do this and the data grows forever until the system is retired/migrated. For small DBs it's not a problem but for this you must go back to your stakeholder and get in writing when you can delete old records then set an automated process or scheduled manual progress to do it. If they need the data long term maybe older data can be moved out of the online system and to an archive or warehouse. Microsoft has some other methods that I have not used. Check those out. https://docs.microsoft.com/en-us/sql/relational-databases/blob/binary-large-object-blob-data-sql-server?view=sql-server-ver15 -- Good luck More on reddit.com
🌐 r/dotnet
111
46
April 28, 2022
Top answer
1 of 1
26

If I understood that right, the backend sends back base64 encoded data. So, you have to decode the response data first. The workflow should look like this:

fetch(fileUploaded.content) 
  .then(response => {
    // response.data -> response data base64 encoded
    // decoding the data via atob()
    const byteArray = new Uint8Array(atob(response.data).split('').map(char => char.charCodeAt(0)));
    return new Blob([byteArray], {type: 'application/pdf'});
  })
  .then(blob => {
    // Here is your URL you can use
    const url = window.URL.createObjectURL(blob);

    // i.e. display the PDF content via iframe
    document.querySelector("iframe").src = url;
  });

Further you can read about

  • Creating a Blob from a base64 string in JavaScript
  • atob()

Edit:

if i want to display the pdf result in my html using . do you have any idea how to do it. thanks in advance

Here is an example how you achieve this: https://stackblitz.com/edit/angular-rwfdhr

Notes:

  • Unfortunately I couldn't make ngx-extended-pdf-viewer work on stackblitz.com. Maybe you can give it a try in your environment. I didn't try it locally. Instead I used pdf-viewer and it just worked out-of-the-box. But I don't see any reason why it shouldn't work with another library, because the workflow has the same principle.

  • My solution is based on my previous answer. Since I don't know your code base exactly, I've done things the way I understood your workflow:

    • There is a service called PdfService (see pdf.service.ts) I created, which basically fetches and returns the base64 encoded PDF content from GitHub Gist that I just created.

    • In the class AppComponent (app.component.ts) the base64 content is decoded and converted to blob and that to a DOMString URL (via URL.createObjectURL).

    • In app.component.html this URL is simply passed to the library for further processing.


Edit 2: The above example does not fit perfectly to Angular way. You should implement the business logic in the services, and keep the controllers as lean as possible.

Here's a demo: https://stackblitz.com/edit/angular-4k63jv

🌐
Ocaso3D
b64encode.com › blog › base64-in-angular
Base64 Encoding and Decoding in Angular: How to Convert Files and PDFs - B64Encode
May 2, 2024 - The component includes an input ... conversion process. When a file is selected, the handleFileInput() method is invoked, which reads the file and uses a FileReader to convert it to a Base64-encoded string....
🌐
Base64.Guru
base64.guru › home › base64 converter › base64 encode
PDF to Base64 | Base64 Encode | Base64 Converter | Base64
Hey! Thanks for sharing. By the way, I do not know any details about your app, but if possible, instead of a blank PDF consider to embed first page of your real PDF file. ... It’s an Angular app where I use the blank page as temporary page while the PDF loads from the server.
🌐
Medium
medium.com › @om_bhandari › convert-image-and-pdf-to-base-64-in-angular-and-java-script-e7aefa7adb9c
Harnessing the Magic of Base64: Converting Images and PDFs with Ease | by Om bhandari | Medium
April 15, 2024 - <input type="file" accept="image/*" (change)="imageChanged($event)"> <input type="file" accept=".pdf" (change)="pdfChanged($event)"> ... public imageToBase64Promise(event: any): Promise<string> { const promise = new Promise<string>((resolve, reject) => { const file: File = event.target.files[0]; if (file) { const reader = new FileReader(); reader.onload = (e: any) => { const image = new Image(); image.src = e.target.result; image.onload = () => { resolve(image.src); } image.onerror = () => { reject("Unable to convert image into base64") } } reader.readAsDataURL(file); } }); return promise; }
🌐
Telerik
telerik.com › knowledge base › creating a base64 string when using the pdfexport
Angular Creating a Base64 String When Using the PDFExport - Kendo UI for Angular
Start a free 30-day trial · Updated on Jan 20, 2026 · How can I create a Base64 string when exporting content to PDF file using PDFExport component? To get a Base64 string and upload it to the server along with other form data: Use the export method of the PDFExport component.
🌐
Codehandbook
codehandbook.org › home › angular, download pdf from base64 string
Angular, Download PDF From BASE64 String -
December 3, 2020 - Logic: You can make use of an anchor tag to download the PDF. You need to create an anchor tag element, set the source of the anchor tag as base64 string, and click the anchor tag.
Find elsewhere
Top answer
1 of 3
42

You can use this code in the showPdf function to generate the PDF, Hope this helps

showPdf() {
        const linkSource = 'data:application/pdf;base64,' + 'JVBERi0xLjMNCiXi48/TDQoNCjEgMCBvYmoNCjw8DQovVHlwZSAvQ2F0YWxvZw0KL091dGxpbmVzIDIgMCBSDQovUGFnZXMgMyAwIFINCj4+DQplbmRvYmoNCg0KMiAwIG9iag0KPDwNCi9UeXBlIC9PdXRsaW5lcw0KL0NvdW50IDANCj4+DQplbmRvYmoNCg0KMyAwIG9iag0KPDwNCi9UeXBlIC9QYWdlcw0KL0NvdW50IDINCi9LaWRzIFsgNCAwIFIgNiAwIFIgXSANCj4+DQplbmRvYmoNCg0KNCAwIG9iag0KPDwNCi9UeXBlIC9QYWdlDQovUGFyZW50IDMgMCBSDQovUmVzb3VyY2VzIDw8DQovRm9udCA8PA0KL0YxIDkgMCBSIA0KPj4NCi9Qcm9jU2V0IDggMCBSDQo+Pg0KL01lZGlhQm94IFswIDAgNjEyLjAwMDAgNzkyLjAwMDBdDQovQ29udGVudHMgNSAwIFINCj4+DQplbmRvYmoNCg0KNSAwIG9iag0KPDwgL0xlbmd0aCAxMDc0ID4+DQpzdHJlYW0NCjIgSg0KQlQNCjAgMCAwIHJnDQovRjEgMDAyNyBUZg0KNTcuMzc1MCA3MjIuMjgwMCBUZA0KKCBBIFNpbXBsZSBQREYgRmlsZSApIFRqDQpFVA0KQlQNCi9GMSAwMDEwIFRmDQo2OS4yNTAwIDY4OC42MDgwIFRkDQooIFRoaXMgaXMgYSBzbWFsbCBkZW1vbnN0cmF0aW9uIC5wZGYgZmlsZSAtICkgVGoNCkVUDQpCVA0KL0YxIDAwMTAgVGYNCjY5LjI1MDAgNjY0LjcwNDAgVGQNCigganVzdCBmb3IgdXNlIGluIHRoZSBWaXJ0dWFsIE1lY2hhbmljcyB0dXRvcmlhbHMuIE1v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Link = document.createElement("a");
        const fileName = "sample.pdf";

        downloadLink.href = linkSource;
        downloadLink.download = fileName;
        downloadLink.click();
    }
2 of 3
9

Your problem is that you are not decoding your base 64 PDF, use the function atob() to achieve this:

var pdfInBase64 = atob(
  'JVBERi0xLjcKCjEgMCBvYmogICUgZW50cnkgcG9pbnQKPDwKICAvVHlwZSAvQ2F0YWxvZwog' +
  'IC9QYWdlcyAyIDAgUgo+PgplbmRvYmoKCjIgMCBvYmoKPDwKICAvVHlwZSAvUGFnZXMKICAv' +
  'TWVkaWFCb3ggWyAwIDAgMjAwIDIwMCBdCiAgL0NvdW50IDEKICAvS2lkcyBbIDMgMCBSIF0K' +
  'Pj4KZW5kb2JqCgozIDAgb2JqCjw8CiAgL1R5cGUgL1BhZ2UKICAvUGFyZW50IDIgMCBSCiAg' +
  'L1Jlc291cmNlcyA8PAogICAgL0ZvbnQgPDwKICAgICAgL0YxIDQgMCBSIAogICAgPj4KICA+' +
  'PgogIC9Db250ZW50cyA1IDAgUgo+PgplbmRvYmoKCjQgMCBvYmoKPDwKICAvVHlwZSAvRm9u' +
  'dAogIC9TdWJ0eXBlIC9UeXBlMQogIC9CYXNlRm9udCAvVGltZXMtUm9tYW4KPj4KZW5kb2Jq' +
  'Cgo1IDAgb2JqICAlIHBhZ2UgY29udGVudAo8PAogIC9MZW5ndGggNDQKPj4Kc3RyZWFtCkJU' +
  'CjcwIDUwIFRECi9GMSAxMiBUZgooSGVsbG8sIHdvcmxkISkgVGoKRVQKZW5kc3RyZWFtCmVu' +
  'ZG9iagoKeHJlZgowIDYKMDAwMDAwMDAwMCA2NTUzNSBmIAowMDAwMDAwMDEwIDAwMDAwIG4g' +
  'CjAwMDAwMDAwNzkgMDAwMDAgbiAKMDAwMDAwMDE3MyAwMDAwMCBuIAowMDAwMDAwMzAxIDAw' +
  'MDAwIG4gCjAwMDAwMDAzODAgMDAwMDAgbiAKdHJhaWxlcgo8PAogIC9TaXplIDYKICAvUm9v' +
  'dCAxIDAgUgo+PgpzdGFydHhyZWYKNDkyCiUlRU9G');
🌐
Syncfusion
ej2.syncfusion.com › documentation › document processing › pdf › pdf viewer › angular › how to › get base string of the loaded document
Get base string of the loaded document in Angular PDF Viewer component | Syncfusion
Step 2: Add the following code snippet to get the base 64 string with button click event. <button (click)="base64ofloadedDocument()">base64Document</button> base64ofloadedDocument() { var viewer = (<any>document.getElementById("pdfViewer")).ej2_instances[0]; viewer.saveAsBlob().then(function (value) { var data = value; var reader = new FileReader(); reader.readAsDataURL(data); reader.onload = () => { var base64data = reader.result; // get base 64 string. console.log(base64data); }; });
🌐
StackBlitz
stackblitz.com › edit › angular-converting-files-to-base64
Angular-Converting-Files-To-Base64 - StackBlitz
An Angular project based on rxjs, tslib, zone.js, @angular/core, @angular/forms, @angular/common, @angular/router, @angular/compiler, @angular/animations, @angular/platform-browser and @angular/platform-browser-dynamic
🌐
Aakashgoplani
blog.aakashgoplani.in › how-to-download-pdf-files-in-angular
How to download PDF files in Angular - Aakash Goplani's Blog
November 14, 2021 - private processFileResponse(fileResponseData: any, fileName: string, render: string): void { if (render === 'base64') { this.base64Response = fileResponseData; const binaryString = window.atob(fileResponseData); const bytes = new Uint8Array(binaryString.length); const binaryToBlob = bytes.map((byte, i) => binaryString.charCodeAt(i)); const blob = new Blob([binaryToBlob], { type: 'application/pdf' }); this.downloadFile(blob, fileName, render); } else { const blob = new Blob([fileResponseData], { type: 'application/pdf' }); this.downloadFile(blob, fileName, render); } }
🌐
StackBlitz
stackblitz.com › edit › dwonload-base64-to-pdf
Dwonload Base64 To Pdf - StackBlitz
Angular example showing how to download and encode image as base64.
🌐
npm
npmjs.com › package › pdf-to-base64
pdf-to-base64 - npm
October 4, 2020 - Generate a base64 from pdf path or url. It was all about converting the pdf into base64 string
      » npm install pdf-to-base64
    
Published: Oct 04, 2020
Version: 1.0.3
🌐
Upmostly
upmostly.com › home › angular › angular file to base64
Converting Files To Base64 In Angular - Upmostly
November 1, 2022 - This means that we either have to use promises or observables, because we are using Angular, let’s use observables. We use a ReplaySubject because we only need to calculate the file once. e.g. If we subscribed multiple times to the same return subject of this method, it doesn’t need to recalculate the base64 since it’s deterministic (The same file is always the same Base64 string).
🌐
npm
npmjs.com › package › base64topdf
base64topdf - npm
August 23, 2017 - * We can convert plain text to RTF. If you wants to encode the pdf file to base64 means you can use this function to Encode it.
      » npm install base64topdf
    
Published: Aug 23, 2017
Version: 1.1.8
Top answer
1 of 2
1

Worried that none of answer mentioned here has pointed this out, I am saying this:

File objects may be obtained from a FileList object returned as a result of a user selecting files using the element, or from a drag and drop operation's DataTransfer object. Source

Therefore only a code like below will work:

const fileInput = document.getElementById("fileInput");
const output = document.getElementById("output");

// Event listener when a user selects a file
fileInput.addEventListener("change", function(event) {
  const file = event.target.files[0]; // Get the selected file

  if (file && file.type === "application/pdf") {
    const reader = new FileReader();

    // Read the file as a Data URL (Base64)
    reader.readAsDataURL(file);

    reader.onload = function() {
      const base64String = reader.result; // Base64 string
      output.textContent = base64String.split(",")[1]; // Display Base64 data (without prefix)
      console.log("Base64 PDF String:", base64String);
      alert(base64String); // as stackoverflow console doesn't display 
      alert("See your browser console as well(not the SO console that will come below empty due to overflow/styling)")
    };

    reader.onerror = function(error) {
      console.error("Error reading file:", error);
    };
  } else {
    alert("Please select a valid PDF file.");
  }
});
<h1>Select a PDF File to Read</h1>
<input type="file" id="fileInput" accept="application/pdf" />
<pre id="output"></pre>

Leo's answer will result in Uncaught TypeError: Failed to construct 'File': The provided value cannot be converted to a sequence. as xRdev said

xRdev's answer

var file = new File(["foo"], "/pdf/test.pdf", {type: 'application/pdf'});

creates a new empty file with just content "foo" inside it, simulating that it is stored in path "/pdf/test.pdf" so eventhough you get base64 it doesnt look like
data:application/pdf;base64,JVBERi0xLjUKJdDUxdgKNSAws2... but instead as data:application/pdf;base64,zsfasf

2 of 2
-2

With fileReader you can convert your file from path like this :

var file = new File("/pdf/test.pdf","r");

function getBase64(file) {
   var reader = new FileReader();
   reader.readAsDataURL(file);
   reader.onload = function () {
     console.log(reader.result);
   };
   reader.onerror = function (error) {
     console.log('Error: ', error);
   };
}
🌐
Facebook
facebook.com › groups › angular.developers.community › posts › 2663940843880271
Anyone suggest , how to convert PDF to Base 64 in ...
Popular groups · Find communities for you · Over 1 billion people across the globe are using Facebook Groups to explore their favorite topics · Log in · Categories · Science & tech · Travel · Animals · Sports & fitness · Entertainment