PDF to image using Angular

We are aware that Angular has been the top UI development platform and that, when combined perfectly with other top platforms, it can achieve amazing results for the custom software development company. Let’s go right to the point and see how to convert PDF to picture in Angular. When converting PDF to PNG or JPG, there are options for cropping, zooming in and out, rotating, and resetting.

Install the necessary packages as mentioned below before starting.

Pre-requisites:

There were packages for directly converting a PDF to an image, but none of them included all of the customizations. We chose three different packages based on the requirements because we couldn’t find all of the features in a single package and implemented them in our application.

The three packages we used are as follows:

  • ng2-pdf-viewer
  • html2canvas
  • cropperjs     

ng2-pdf-viewer: The ng2-pdf-viewer package is designed specifically for creating or implementing PDF viewer components in Angular applications. It is a popular module for handling PDF-related tasks in angular; this plugin offers numerous features for pdf implementation in angular.

html2canvas: Html2Canvas is a JavaScript library that allows you to take a screenshot of the entire web page or a specific section. It technically does not take a screenshot, but rather creates the view based on the information available on the page.

Cropperjs: Cropper.js is the pure JavaScript version of the jQuery Image Cropper plugin, which allows you to crop any image with a variety of features.

How to Convert a PDF to an Image in Angular?    

1. Make an Angular application.

  • Run the following command to create an Angular application.

ng new pdf-to-image

      The Angular CLI will make a folder and install the necessary packages and dependencies

  • Navigate to the projects page.

cd  pdf-to-images

2. Run Angular application.

Open the terminal and type a command to run your application locally.

ng serve

3. Install bootstrap.

Install the bootstrap library for the UI part with the command below.

npm install bootstrap

After installation, add the bootstrap CSS path to the styles array in the angular.json file.

“styles”: [

      “node_modules/bootstrap/dist/css/bootstrap.min.css”,

      “src/styles.scss”

]

4. Install the package ng2-pdf-viewer.

To display the pdf on the web browser page, the ng2-pdf-viewer package is used. Run the following command to install the package.

npm i ng2-pdf-viewer

This package will be visible in the package.json file after installation.

“ng2-pdf-viewer”: “^6.4.1”

5. Uploading PDF.

In the app.component.html file, we will now add an input type. To add the UI part for uploading the pdf, use the code snippet below.

//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)”>

In the same file, create a function for uploading PDFs.

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 determine whether or not it is a PDF file. So we’ll look at the file type here. If it is not a pdf, it will display a message or call the onload() function to convert it to base 64.

6. Show pdf in browser.

We will bind the pdfsrc variable in the src input property and also add the displayed page’s page input property. Set the [show-all] input property to true to display all pages; otherwise, set it to false. Other properties are also available 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>

The pdf is fully rendered on the screen after the afterLoadComplete($event) function is called. You can also use this function to display the total number of pages. To accomplish this, use the numPages property to determine the total number of pages, as shown below.

afterLoadComplete(pdf: PDFDocumentProxy) {

  this.totalPages = pdf.numPages;

}

7. Previous and Next page.

This step is optional because you will display all of the pages in the browser at once; if you prefer, you can skip it. Please ensure that the [show-all] property in the pdf-viewer is set to false. If it is true, we will be unable to customize pdf images in the browser. First, in app.component.html, add two buttons.

<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 – {{ currpage }} 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>

In app.component.ts, add business logic for the previous and next buttons.

public previous() {

  if (this. currpage > 0) {

    if (this.currpage == 1) {

      this. currpage = this.totalPages;

    } else {

      this. currpage –;

    }

  }

}

public next() {

  if (this.totalPages > this. currpage) {

    this. currpage = this. currpage + 1 ;

  } else {

    this. currpage = 1;

  }

}

8. Install the html2canvas, cropperjs, and jquery libraries.

In the angular.json file, include the cropperjs CSS 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”

           ]

In the angular.json file, include the cropperjs and jqueryjs files.

“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”

           ]

In the app.components.ts, import these two packages

import html2canvas from ‘html2canvas’;

import Cropper from ‘cropperjs’;

9. Install the html2canvas, cropperjs, and jquery libraries.

Let’s now focus on crop functionality. Here’s the user interface. Add a button to crop 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 to convert HTML pages into canvas images. Canvas.toDataUrl() is used to obtain the HTML page’s base 64 string. You can get the image by using DOM properties.

Jquery is used to dynamically set the image’s src attribute and add the class. The cropper box is initialized using the ready class.

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 is a package that is used to crop images, zoom them, set the background, move them, and many other things. You can learn more about the package and use its features.

10. Zoom in and Out.

Zoom functionality is now available. In app.component.html, add two buttons for the zoom feature.

  • Zoom-In User Interface:

<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>

  • Zoom-Out User Interface:

<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>

You must be certain when to initialize the cropper set zoomable true; otherwise, it will not function.

public zoomOut() {

  this.cropper.zoom(0.1)

}

public zoomIn() {

this.cropper.zoom(-0.1)

}

11. Zooming with the Range Slider.

Make the range input type and bind the change event to it.

<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)”>

In app.component.ts, include the onRange() method.

public onRange(event: any) {

  this.cropper.zoomTo(event.target.value)

}

12. Download the image in pdf format.

In the HTML file, add a download button.     

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

Cropper has a getcroppedCanvas() method that returns the cropped canvas, which is then 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();

}

13. Reset the Cropped Image.

Make a Reset button in the 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 simply destroy the cropper using the destroy() function and then remove the crop box using the cropper’s clear() method.

public reset() {

  this.isCropImage = false;

  this.cropper.clear();

  this.cropper.destroy();

}

Conclusion:

The best UI development platform, Angular, may produce outstanding outcomes when integrated effectively with other leading technologies. In this blog post, we took a step-by-step look at how to convert PDF to image in Angular. In addition, we also examined the prerequisites and implemented features like Crop, Zoom, Rotate, and Reset.

By Anurag Rathod

Anurag Rathod is an Editor of Appclonescript.com, who is passionate for app-based startup solutions and on-demand business ideas. He believes in spreading tech trends. He is an avid reader and loves thinking out of the box to promote new technologies.