Export or Open PDF in Angular using JSPDF

In this article, we saw how to export or open PDF in angular using JSPDF. In the last article, we discuss how to read CSV we have added option their to open PDF & export PDF. Let’s create a new project that you need to run following command


ng new pdf-generate

“pdf-generate” you need to write your application’s name. Then it will take some time to create the project. After successfully installing that, you need to go to their directory. For example “cd pdf-generate”. To Run angular applications, it required to run “ng serve”.


After we need to install “JSPDF”


npm install jspdf

After install module we can use these module in our component. we need to import “jsPDF”.


import jspdf from 'jspdf';

We need to create function for open pdf & download pdf functions. In that functions we use “new jsPDF()” we need tp pass the PDF size. We have used element refrance to get the html to print the pdf.

Open Pdf Function


 @ViewChild('htmlData', {static: false}) htmlData:ElementRef;

//Open Pdf File
openPDF(){
    let DATA = this.htmlData.nativeElement;
    let doc = new jspdf('p','pt', 'a4');

   doc.setProperties({
       title: "new Report"
  });
   doc.fromHTML(DATA.innerHTML,30 ,30);
   window.open(URL.createObjectURL(doc.output("blob")))
  }

Download Pdf Function


//Download Pdf File
downloadPDF(){
    let DATA = this.htmlData.nativeElement;
    let doc = new jspdf('p','pt', 'a4');

    let handleElement = {
      '#editor':function(element,renderer){
        return true;
      }
    };
    doc.fromHTML(DATA.innerHTML,15,15,{
      'width': 200,
      'elementHandlers': handleElement
    });

    doc.save('csvpdf.pdf');
  }

Display below is the code for the app.component.ts ,app.component.html,app.component.css


/*
https://www.eduforbetterment.com/
*/
import { Component, VERSION ,ViewChild ,ElementRef} from '@angular/core';
import jspdf from 'jspdf';

export class CsvData {
    public id: any;
    public min: any;
    public max: any;
    public score: any;
}

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  name = 'Angular ' + VERSION.major;
  public records: any[] = [];
  @ViewChild('csvReader') csvReader: any;
  @ViewChild('htmlData', {static: false}) htmlData:ElementRef;
  jsondatadisplay:any;

  uploadListener($event: any): void {

    let text = [];
    let files = $event.srcElement.files;

    if (this.isValidCSVFile(files[0])) {

      let input = $event.target;
      let reader = new FileReader();
      reader.readAsText(input.files[0]);

      reader.onload = () => {
        let csvData = reader.result;
        let csvRecordsArray = (csvData).split(/\r\n|\n/);

        let headersRow = this.getHeaderArray(csvRecordsArray);

        this.records = this.getDataRecordsArrayFromCSVFile(csvRecordsArray, headersRow.length);
      };

      reader.onerror = function () {
        console.log('error is occured while reading file!');
      };

    } else {
      alert("Please import valid .csv file.");
      this.fileReset();
    }
  }

  getDataRecordsArrayFromCSVFile(csvRecordsArray: any, headerLength: any) {
    let csvArr = [];
//csvRecordsArray.length
    for (let i = 1; i < 30; i++) {
      let curruntRecord = (csvRecordsArray[i]).split(',');
      if (curruntRecord.length == headerLength) {
        let csvRecord: CsvData = new CsvData();
        csvRecord.id = curruntRecord[0].trim();
        csvRecord.min = curruntRecord[1].trim();
        csvRecord.max = curruntRecord[2].trim();
        csvRecord.score = curruntRecord[3].trim();
        csvArr.push(csvRecord);
      }
    }
    return csvArr;
  }

//check etension
  isValidCSVFile(file: any) {
    return file.name.endsWith(".csv");
  }

  getHeaderArray(csvRecordsArr: any) {
    let headers = (csvRecordsArr[0]).split(',');
    let headerArray = [];
    for (let j = 0; j < headers.length; j++) {
      headerArray.push(headers[j]);
    }
    return headerArray;
  }

  fileReset() {
    this.csvReader.nativeElement.value = "";
    this.records = [];
    this.jsondatadisplay = '';
  }

  getJsonData(){
    this.jsondatadisplay = JSON.stringify(this.records);
  }

  openPDF(){
    let DATA = this.htmlData.nativeElement;
    let doc = new jspdf('p','pt', 'a4');
   
   // doc.output('dataurlnewwindow');
   doc.setProperties({
       title: "new Report"
  });
   doc.fromHTML(DATA.innerHTML,30 ,30);
  //doc.output('dataurlnewwindow');
   window.open(URL.createObjectURL(doc.output("blob")))

  }

  downloadPDF(){
    let DATA = this.htmlData.nativeElement;
    let doc = new jspdf('p','pt', 'a4');

    let handleElement = {
      '#editor':function(element,renderer){
        return true;
      }
    };
    doc.fromHTML(DATA.innerHTML,15,15,{
      'width': 200,
      'elementHandlers': handleElement
    });

    doc.save('csvpdf.pdf');
  }


}


<div class="container">
  
  <div class="card">
    <div class="card-header">
      Upload csv to read
    </div>
    <div class="card-body">

      <input type="file" #csvReader name="Upload CSV" id="txtFileUpload" (change)="uploadListener($event)" accept=".csv" />

    </div>
  </div>

<a href="javascript:;" *ngIf="records.length > 0" (click)="getJsonData()" class="btn btn-primary">Convert Json </a>

<a href="javascript:;" *ngIf="records.length > 0" (click)="fileReset()" class="btn btn-primary">Reset </a>  

<div class="col-md-4 text-right"  *ngIf="records.length > 0" >
   <button class="btn btn-success btn-block" (click)="openPDF()">Open PDF</button>
   <button class="btn btn-danger btn-block" (click)="downloadPDF()">Download PDF</button>
</div>

  <div>
    {{jsondatadisplay}}
  </div>
<div class="col-md-8" id="htmlData" #htmlData>

  <table class="table"  *ngIf="records.length > 0">
    <thead class="thead-dark" >
      <tr>
        <th scope="col">#</th>
        <th scope="col">Min</th>
        <th scope="col">Max</th>
        <th scope="col">Score</th>
      </tr>
    </thead>
    <tbody>
      <tr *ngFor="let record of records;let i = index;">
        <th scope="row">{{record.id}}</th>
        <td>{{record.min}}</td>
        <td>{{record.max}}</td>
        <td>{{record.score}}</td>
      </tr>
  
    </tbody>
  </table>
</div>
</div>

[tab title="index.html"]


<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">

<my-app>loading</my-app>




Output

Below is the full embeded code export or Open PDF in Angular using JSPDF. you can easily used in your application.
Example

Spread the love
  •  
  •  
  •  
  •  
  • 2
  • 2
  •  
  •