Angular View Blob (Base64) Image and Print PDF

Abhay Ahire
2 min readAug 14, 2022

Hello Folks,
I was working on quick fix to add print pdf feature in angular.
But didn’t found relevant resource around it. So writing this blog for you guys.
In this short blog we are going to see how we can do that
1. Render base64 image into browser.
2. To print that image using angular with the help of JavaScript.

Let’s generate angular application from scratch
Use ng new print-pdfcommand to create new angular project.
Now as first thing we need to show image into browser.
We have added static base64 encoded string into assets folder within data.json file. You can check github link to see the contents.
We’ll use that string to render image into browser.
But what’s base64? Base64 is to encode files into string format that can be transferred over the network and can again be decoded to get the same file.
Let’s see how to do that
Let’s create a http service to load that static base64 string for us.
Create Http Service named data-service as follows
You can use ng g s datacommand to generate it.

Now In main app component , inject data-service as follows

Along with dataService we have injected DomSanitizer to allow us to render image from base64 string into browser. In ngOnInit, we are calling dataService to load base64 string and store it into base64String.
Before storing it, we are sanitizing it using DomSanitizer’s bypassSecurityTrustUrl function.
Let’s add image tag in app component to render the image.

Now run your application using ng serve
Bravo!!! Our first job is completed…
Now we’ll see how to add Print PDF feature.
Add a simple button in our page to open print view.

In app.component.ts add following printPDF() function.

Here we are referecing target element to be printed by id `printContainer`
We are using javascript to open new window using window.open()
You can adjust new window’s location using css specified as a third argument.

Now let’s run our application again.
It’s opening print window as expected after clicking on print button.

Now you can use more controls as Saving PDF, changing layout mode.
Cool!!!
You can checkout ready codebase at https://github.com/abhay-321/angular-print-pdf.
Thanks for reading.. :)

--

--

Abhay Ahire

Full stack Dev with Angular, Java , Node and Devops Engg AWS