How to Convert PDF to Image in Angular 11

Every client’s requirement varies from project to project. A few days back, my client wanted me to add a feature for converting a PDF to various Images with some customized functionalities-

  • Crop
  • Zoom In and Out
  • Rotate
  • Reset

Let’s have a look at how to convert PDF to image in Angular 11: Convert PDF to PNG or JPG with Crop, Zoom in and out, Rotate, and Reset Features.

Goal: What are we building?

Expectations and Requirements

  • Download pages of PDF with the image format (PNG or JPG).
  • Customize the pages with different functionalities like crop, zoom, reset, and rotate.
  • Download the customized or unchanged page.

Video of the application

Install Packages: ng2-pdf-viewer, html2canvas, and cropperjs

There were packages for converting a PDF to Imagedirectly, but none offered all the customizations together. It took quite some time to find the packages because of the requirements and expectations stated above. As I could not find all the features in a single package, I chose three different packages according to the requirement and implemented them in my application. Don’t worry; I have created a small demo application whose Github link is attached at the end of this tutorial; you can clone that and play around with the code.

Here are the three packages that I have used:
1. ng2-pdf-viewer
2. html2canvas
3. cropperjs

ng2-pdf-viewer- It is used for displaying the pdf on a web page. We will bind the URL of the pdf from our local system and start implementing the package. It’s very simple to attach the pdf file from the input file type. Even if you’re using it for the first time, you won’t find it difficult to implement.

html2canvas- It is used to convert HTML pages to Canvas as we want to download various pdf pages.

cropperjs – It is used to crop, zoom, and rotate the pdf pages. There are many other functionalities available in this package: move, zoom with 100%, set crop box size, etc.

Steps to Convert PDF to Image in Angular 11

Now it’s time to code! Follow these steps to convert PDF to Image in Angular 11.

1. Create Angular application

  • Create Angular application using the below command
ng new pdf-to-image

Angular CLI will create a folder and install the required packages & dependencies.

  • Navigate to project
cd  pdf-to-images

2. Run Angular application

Open the terminal and enter a command to run your application on your local machine.

ng serve

Your application will be running on- http://localhost:4200.

3. Install bootstrap

Use the below command to install the bootstrap library for the UI part.

npm install bootstrap

After installation, add the css path of bootstrap in the styles array in the angular.json file.

"styles": [
      "node_modules/bootstrap/dist/css/bootstrap.min.css",
      "src/styles.scss"
]

4. Install ng2-pdf-viewer package

The ng2-pdf-viewer package is used to display the pdf on the web browser page. Use the below command to install the package-

npm i ng2-pdf-viewer

After installation, you can see this package in the package.json file.

"ng2-pdf-viewer": "^6.4.1"

5. Uploading PDF

Now, we will be adding input type in the app.component.html file. Use the below code snippet to add the UI part for uploading the pdf.

//app.component.html

<label for="formFile" class="form-label"> Please Select File:</label>
<input class="form-control" type="file" id="upload-doc" accept=".pdf"  (change)="uploadFile($event)">

Create one function for uploading pdf in the same file.

public uploadFile(event:any) {
   let $img: any = document.querySelector('#upload-doc');
   if(event.target.files[0].type == 'application/pdf'){
     if (typeof (FileReader) !== 'undefined') {
       let reader = new FileReader();
       reader.onload = (e: any) => {
         this.pdfSrc = e.target.result;
       };
       this.isPdfUploaded = true;
       reader.readAsArrayBuffer($img.files[0]);
     }
   } else{
     alert('Please upload pdf file')
   }
}

The function would take the target file and validate it to check if it’s pdf or not.

So here, we will check the file type. If it is not a pdf, it will show the message or execute the onload() function to convert the pdf into base 64.

6. Display pdf in the browser

We will bind the pdfsrc variable in the src input property and also add the page input property of the displayed page.

If you want to display all the pages, set [show-all] input property to true otherwise false. You can check other properties also in the ng2-pdf-viewer package.

<pdf-viewer [src]="pdfSrc" [render-text]="true" [page]="currentpage"  [show-all]="false" [original-size]="true" [fit-to-page]="false" (after-load-complete)="afterLoadComplete($event)" style="display block;"></pdf-viewer>

Once the afterLoadComplete($event) function is executed, the pdf is fully rendered on the screen. You can display the total number of pages using this function as well. For that, use the numPages property to get the total number of pages, as shown below.

afterLoadComplete(pdf: PDFDocumentProxy) {
   this.totalPages = pdf.numPages;
 }

Go to the – http://localhost:4200.

And you’ll see something like this. Ignore the previous/next, crop, and download part for now; we will implement that in the coming sections.

Convert PDF to Image

7. Previous and Next page

This step is optional as you will show all the pages in the browser at a time sp; if you want, you can skip this step.

Please check that the [show-all] property is false in the pdf-viewer. If it is not false, then we won’t be able to customize pdf images in the browser.

First of all, create two buttons in app.component.html.

<div class="page-div">
      <button (click)="previous()" class="btn btn-success">
        <i class="fa fa-angle-left font-weight-bold"aria-hidden="true"></i>
      </button>
      <p class="pagescount">Pages - {{currentpage}} of {{totalPages}}</p>
      <button (click)="next()" class="btn btn-success">
       <i class="fa fa-angle-right font-weight-bold"aria-hidden="true"></i>
      </button>
</div>

Add business logic for previous and next buttons in app.component.ts.

public previous() {
   if (this.currentpage > 0) {
     if (this.currentpage == 1) {
       this.currentpage = this.totalPages;
     } else {
       this.currentpage--;
     }
   }
 }

 public next() {
   if (this.totalPages > this.currentpage) {
     this.currentpage = this.currentpage + 1 ;
   } else {
     this.currentpage = 1;
   }
 }

8. Install html2canvas, cropperjs, and jquery

Add the cropperjs css file in the angular.json file.

"styles": [
             "node_modules/cropperjs/dist/cropper.min.css",
             "node_modules/bootstrap/dist/css/bootstrap.css",
             "node_modules/bootstrap/dist/css/bootstrap.min.css",
             "src/styles.scss"
           ]

Add the cropperjs file and jqueryjs file in the angular.json file.

"scripts": [
             "node_modules/jquery/dist/jquery.min.js",
             "node_modules/bootstrap/dist/js/bootstrap.js",
             "node_modules/bootstrap/dist/js/bootstrap.min.js",
             "node_modules/cropperjs/dist/cropper.min.js"
           ]

Import these two packages in the app.component ts

import html2canvas from 'html2canvas';
import Cropper from 'cropperjs';

9. Crop the Image

Now let’s work on crop functionality.

Here’s the UI part. Add one button for cropping the pdf pages.

<button (click)="crop()" class="btn btn-warning button-margin"                  data-toggle="tooltip" data-placement="top" title="Crop">
      <i class="fa fa-crop" aria-hidden="true"></i>
</button>

The html2canvas package is used for converting HTML pages into the canvas.

Canvas.toDataUrl() function is used for getting the base 64 string of the HTML page. You can use DOM properties for getting the image.

Jquery is used to set the src attribute of the image and add the class dynamically. The ready class is used for initializing the cropper box.

public crop() {
   html2canvas(document.querySelector(".pdf-container") as HTMLElement).then((canvas: any) => {
     let ctx = canvas.getContext('2d');
     ctx.scale(3, 3);
     let image = canvas.toDataURL("image/png").replace("image/png", "image/png");
     $("#cropper-img").attr('src', image);
     $('#cropper-img').addClass('ready');
     this.isCropImage = true
     let cropImg: any = document.getElementById('cropper-img');
     this.cropper = new Cropper(cropImg, {
       zoomable: true,
       background: false,
       guides: false,
       highlight: false,
       movable: false,
       ready: (e) => {
         let cropper = this.cropper;
       },
       crop: (e) => {
       }
     });
   })
 }

Cropperjs package is used to crop the images, zoom them, set background, move, and many more. You can explore more about the package and make use of its properties.

Tip- I would like to share my insight with you: the cropperjs package is very good compared to the angular-cropperjs package. When you install the angular cropper js package, it works fine, but you will encounter bugs as you start using its properties. It might also break your functionality as there is no way to initialize and destroy the cropper properly in this package.

10. Zoom In and Out

It’s time for Zoom functionality. Create two buttons in app.component.html for the zoom feature.

UI for Zoom In

 <button (click)="zoomIn()" data-toggle="tooltip" data-placement="top" title="Zoom In" *ngIf="isCropImage" class="btn btn-light button-margin">
      <i class="fa fa-search-plus" aria-hidden="true"></i>
  </button>

UI for Zoom Out

 <button (click)="zoomOut()" data-toggle="tooltip" data-placement="top" title="Zoom Out" *ngIf="isCropImage" class="btn btn-light button-margin">
      <i class="fa fa-search-plus" aria-hidden="true"></i>
 </button>

This functionality is used for zooming in the image. You can set a picture with a zoom feature.

You must be sure about when to initialize the cropper set zoomable true; otherwise, it can’t work.

 public zoomOut() {
   this.cropper.zoom(0.1)
 }
 public zoomIn() {
   this.cropper.zoom(-0.1)
 }

11. Zoom Functionality with Range Slider

If you don’t want to control zoom functionality using buttons, you can go for a slider.

Create the range input type and bind the change event on the input type.

<input *ngIf="isCropImage" data-toggle="tooltip" data-placement="top" title="Crop" type="range" min="0.1" max="1" step="0.1" class="slider button-margin" id="myRange" (change)="onRange($event)">

Add onRange() method in app.component.ts. Cropper has a zoomTo() method for zooming the image.

public onRange(event: any) {
   this.cropper.zoomTo(event.target.value)
 }

12. Rotate Images

Create one button for rotating the image in your app.component.html file.

<button (click)="onRotate()" data-toggle="tooltip" data-placement="top"     title="Rotate" *ngIf="isCropImage" class="btn btn-warning button-margin">
<i  class="fa fa-Rotate" aria-hidden="true"></i>
</button>

Add onRotate() method in app.component.ts. Cropper has a (rotate) method for rotating the image. Here we will pass the value for which direction to rotate the image like 90, 180, 274, 360 values.

public onRotate() {
   this.cropper.rotate(90)
 }

13. Download the pdf image

Create a download button in the HTML file.

<button (click)="download()" class="btn btn-primary button-margin">Download</button>

It’s very simple to download a pdf image by using the html2 canvas package. Here we will write the logic for downloading crop images and without crop images. Check the condition for the same.

Cropper has a getcroppedCanvas() method for getting the cropped canvas, and that canvas is passed as a parameter to the getCanvasDownload() function.

public download() {
   if (this.isCropImage) {
     let canvas = this.cropper.getCroppedCanvas();
     this.getCanvasToDownload(canvas)
   } else {
     html2canvas(document.querySelector(".pdf-container") as HTMLElement).then((canvas: any) => {
       this.getCanvasToDownload(canvas)
     })
   }
 }

 private getCanvasToDownload(canvas: any) {
   let ctx = canvas.getContext('2d');
   ctx.scale(3, 3);
   let image = canvas.toDataURL("image/png").replace("image/png", "image/png");
   var link = document.createElement('a');
   link.download = "my-image.png";
   link.href = image;
   link.click();
 }

Let’s see getCanvasToDownload() function does-

  • take canvas as an argument
  • convert into data URL
  • get the base64 string
  • set the string in the href attribute of an anchor tag
  • download that image.

14. Reset the Cropped Image

If you wish to undo all the changes and reset it to the original, then you can use this functionality.

Create Reset button in HTML file

<button (click)="reset()" data-toggle="tooltip" data-placement="top"   title="Reset" *ngIf="isCropImage"  class="btn btn-danger button-margin">
<i class="fa fa-undo" aria-hidden="true"></i>
</button>

In the reset() method, we just need to destroy the cropper using destroy() function and then remove the crop box by using the clear() method of a cropper.

public reset() {
   this.isCropImage = false;
   this.cropper.clear();
   this.cropper.destroy();
 }

The entire source code is available here- GitHub Repository. You can clone it and play around with the code.

Conclusion

So, this was a tutorial on how to convert PDF to Image in Angular 11 with Crop, Zoom, Rotate, and Reset Features. I hope it helps to find a solution if you are stuck with such requirements. After researching a lot, I came up with these three packages. If you have a better solution, then feel free to comment!

Visit Angular Tutorials for more such technical blogs.

If you are looking for skilled and dedicated Angular developers to fulfill your project’s unique business requirements, feel free to get in touch with us to hire Angular developers from us.

How Can We Help You?

X

Get Our Newsletter

Be The First To Get The Latest Updates And Tutorials.

Request A Free Consultation