Export PDF in Angular with JSPDF.

In this post we are going to create an Angular 12 application and export a PDF file using jspdf library.

jspdf is a very niche library to generate PDFs in JavaScript. We can create PDFs for various types of forms or documents, like, work-orders, reports, invoices…etc. Checkout their website for various functionalities like using third party tools, browser print methods. Once we create the PDF we can also download it on the client-side.

Let us start with creating new Angular project.

ng new angular-jspdf-example
cd angular-jspdf-example/

Next, let’s also install Bootstrap CSS framework to create our table UI.

npm install bootstrap

Adding Bootstrap to Angular project…Open styles.scss (I have created my Angular project using SCSS) and add below line to import the Bootstrap styles.

// Note: We are importing all the bootstrap styles but you wouldn't need that.
@import './node_modules/bootstrap/scss/bootstrap';

Install jspdf.

npm install jspdf

We now have our Angular project ready with all the needed dependencies. Run the application to check if all is good!!.

ng serve

Cool, we are now ready to add code for our PDF file. Open app.component.html (template) file and add below code.

<div class="row">
  <div class="col-md-12">
    <table class="table table-striped">
      <thead>
      <tr>
        <th scope="col">#</th>
        <th scope="col">First</th>
        <th scope="col">Last</th>
        <th scope="col">Handle</th>
      </tr>
      </thead>
      <tbody>
      <tr *ngFor="let item of users">
        <th scope="row">{{ item.uid }}</th>
        <td>{{ item.first }}</td>
        <td>{{ item.last }}</td>
        <td>{{ item.handle }}</td>
      </tr>
      </tbody>
    </table>
    <button type="button" class="btn btn-primary" (click)="exportDataToPDF()">Export to PDF</button>
  </div>
</div>

Here we have a table (Note: grid and table styles are from Bootstrap) to show our users data and a button to export this table data to our PDF file. And in the component class file we are going to define the users data and also declare exportDataToPDF function to export the data to our PDF file.

Declare Users data, like below.

users = [
  {
    uid: '1',
    first: 'Mark',
    last: 'Otto',
    handle: '@mdo'
  },
  {
    uid: '2',
    first: 'Jacob',
    last: 'Thornton',
    handle: '@fat'
  },
  {
    uid: '2',
    first: 'Larry the Bird',
    last: 'Thornton',
    handle: '@twitter'
  }
];

We are using jspdf library functions, so import jspdf.

import { CellConfig, jsPDF } from 'jspdf';

Declare the ‘Export to PDF‘ handler function and necessary functions to construct table data from jspdf library.

exportDataToPDF() {
  // Creating a unique file name for my PDF
  const fileName = this.title.replace(' ', '_') + '_' + Math.floor((Math.random() * 1000000) + 1) + '.pdf';
  // Default export is a4 paper, portrait, using millimeters for units
  const doc = new jsPDF();
  doc.setFontSize(20);
  doc.setFont('helvetica', 'bold');
  const titleXPos = (doc.internal.pageSize.getWidth() / 2) - (doc.getTextWidth(this.title) / 2);
  doc.text(this.title, titleXPos, 20);
  doc.setFont('helvetica', 'normal');
  doc.setFontSize(14);
  doc.table(10, 35, this._getDataForPdfTable(), this._createHeadersForPdfTable([
    'uid', 'first', 'last', 'handle'
  ]), { autoSize: false });
  doc.save(fileName);
}

private _createHeadersForPdfTable(keys: string[]) {
  const result: CellConfig[] = [];
  for (let i = 0; i < keys.length; i += 1) {
    result.push({
      name: keys[i],
      prompt: keys[i],
      width: 55,
      align: 'center',
      padding: 10
    });
  }
  return result;
}

private _getDataForPdfTable() {
  const data = [];
  for (let i = 0; i < this.users.length; i++) {
    data.push({
      uid: this.users[i].uid,
      first: this.users[i].first,
      last: this.users[i].last,
      handle: this.users[i].handle,
    });
  }
  return data;
}

Now if you click the button you should see the PDF file exported with data from the table in table fashion.

But let’s take a moment to understand above functions.

  • const doc = new jsPDF(); will create a document instance for the PDF so we can call the required functions from the library to create our PDF file.
  • We are using few functions like setFontSize(), setFont(), text(), table() from the jspdf library to create the PDF as in required format.
  • save() function will export the PDF file.
  • Checkout the website for more details about the parameters these functions need.
Conclusion
  • We are able to create Angular project and install jspdf.
  • We are able to create table using jspdf and export PDF file.
  • We are able to set title, set font size.. etc for our PDF file.

Checkout complete code on Github and enjoy the demo.

Versions

  • Angular – ~12.2.0
  • Bootstrap – ^5.1.3
  • jspdf – ^2.4.0

Published by Kumar Gandhi K

Hi! I’m Kumar and I live in Bangalore (IN) with my family. By profession I’m a Web Developer experienced in a vast variety of frameworks and technologies, like, HTML, CSS, JavaScript, Angular, Bootstrap… Using these i have built or sometimes maintained mid market and enterprise level applications. I worked for few software companies over the years and on few domains like finance, field-service and storage. I also did consulting job at one point. I am loyal and hard (or for better word smart) working individual. In my free time I read books, in fact I buy a lot of books hoping that some day I might find all the time in the world to read them and I also enjoy watching TV.

2 thoughts on “Export PDF in Angular with JSPDF.

Leave a comment