Client Side PDF Generation In Angular With PDFMake

Generating a PDF in any business application is a common use case. For example, we generate reports, invoices, blog content, documents, guidelines, forms, etc in PDF form.
 
There are various ways to generate PDFs in web applications,
  1. Server Side PDF Generation
    We can generate PDF on the server-side and download it on the client-side application. This approach is useful when you have a very large dataset which you want to generate in PDF. This approach will require the extra API call on the server to get the PDF which can be extra overhead if your PDF is small.
  2. Client-Side PDF Generation
    Another popular approach is we generate PDF on the client-side application directly in the browser. This approach is very common when you want to generate a small size PDF for reports, invoices, forms, etc. This approach also gives us an advantage of real-time pdf generation; e.g. We can generate the PDF based on the user interaction. 
We can generate PDF on client side in the following ways,
  1. Using the browser window.print() function
    This is a straightforward approach, where we directly save the web page as a PDF form.- This approach doesn't require any other implementation. also, we can control the divisions which we want to show in PDF up to some level using CSS. Using this approach we have to create the HTML page for our PDF layout and then execute the window.print() to save it as PDF. This approach is not useful when we want to generate custom PDF (not the same as a web page).

  2. Using JavaScript Library
    This helps us to generate custom PDF layouts, add the styling, images, meta information, tables, list, and many more things. This gives us more control over the PDF formatting. 
In this article, we will use JavaScript Library to generate PDF in the browser.
 
There are two javascript libraries available to generate pdf on the client-side.
In this article, we will use PDFMake to export a PDF in an angular application. We will create the Invoice Generator Angular application with PDFMake. We will get the invoice details from form and generate the PDF.

We will demonstrate the various features of PDFMake like columns, table, list, QR code, Custom Styles. At the end of this article, our application will look like this,
 
Invoice Generator Application : Angular Export to PDF using PDFMake
 
Before we start with application development let's see an introduction about PDFMake. 
 

PDFMake Introduction 

 
PDFMake is a popular client-side and server-side pdf generation javascript library.
 
It provides various features like adding tables, columns, lists, links, images, styling, headers/footers, document meta-information, and all other important PDF generation features.
 
It also provides some extraordinary features like adding QR Code, Watermark, Table of Content, Encryption and Access Privileges.
 
It has around 8.4 K stars and 1.5 K forks on GitHub.
 
Now, let's see How to generate PDF with PDFMake in Angular using Invoice Generator demo application. Let's start the step by step implementation.
 

Create an Angular Application

 
We will create a new angular application using the following Angular CLI command. 
 
Note
If you want to generate PDF in your existing application then skip this step.
  1. ng new [application-name]  
At the time of writing this article, I was using Angular 10.
Install PDFMake library
Execute the following command to Install the PDFMake library.
  1. npm install --save pdfmake  
Once it is installed, to use PDFMake in the browser we need to import pdfmake.js and vfs_fonts.js file. Add the following statements on top of the component or service where you want to use PDFMake.
 
In our application, we will generate a PDF in the AppComponent. So we will add the following two statements on top of the AppComponent. 
  1. import pdfMake from "pdfmake/build/pdfmake";  
  2. import pdfFonts from "pdfmake/build/vfs_fonts";  
  3. pdfMake.vfs = pdfFonts.pdfMake.vfs;   

Generate the Simple PDF for testing the PDFMake Setup

 
PDFMake follows the declarative approach. It means, you’ll never have to calculate positions manually or use commands like writeText(text, x, y), moveDown etc…, as you would with a lot of other libraries. - From PDFMake Official Document 
 
The most fundamental concept to be mastered is the document definition object.  The document definition object is a kind of JSON object where you provide all your PDF configuration with different keys. Like content, column, table, ul, image, style, etc.
 
For example, we can generate the simple PDF with header and content as follows
  1. /** app.component.ts**/  
  2.   
  3. import { Component } from '@angular/core';  
  4.   
  5. import pdfMake from "pdfmake/build/pdfmake";  
  6. import pdfFonts from "pdfmake/build/vfs_fonts";  
  7. pdfMake.vfs = pdfFonts.pdfMake.vfs;  
  8.   
  9. export class AppComponent {   
  10.   
  11.   generatePDF() {  
  12.     let docDefinition = {  
  13.       header: 'C#Corner PDF Header',  
  14.       content: 'Sample PDF generated with Angular and PDFMake for C#Corner Blog'  
  15.     };  
  16.    
  17.     pdfMake.createPdf(docDefinition).open();  
  18.   }  
  19. }  
  1. <!-- app.component.html -->
  2. <button (click)="generatePDF()">Generate PDF</button>  
In generatePDF() we have added a simple document definition object to generate simple PDF. pdfMake has createPdf(docDefinition) method to create PDF from document definition object and open() method to open created PDF in browser.
 
It also has other inbuilt methods to download and print PDF.
  • pdfMake.createPDF(docDefinition).open();
  • pdfMake.createPDF(docDefinition).download();
  • pdfMake.createPDF(docDefinition).print();
So now when you will click on Generate PDF button, you will get PDF as below
 
Simple PDF Generated with Angular and PDFMake
 
If you can generate this PDF then Great . You have successfully set up the PDFMake in Angular application. If you are facing any issue then check the above steps again, even if it is not resolved comment in the below comment section. 
 
Our basic application set up is done. Now let's start with building an invoice generator application.
 

Invoice Generator Application

 
We will first design the invoice form in app.component.html, from where we will get the customer details, order details, and additional details.
 
This page will also have three buttons - Download Invoice, Print Invoice, and Open Invoice.
  1. <!-- app.component.html : Invoice Form UI -->    
  2.     
  3. <nav class="navbar navbar-expand-sm navbar-dark bg-secondary">    
  4.     <a class="navbar-brand" href="#">INVOICE GENERATOR</a>    
  5. </nav>    
  6.     
  7. <div class="container-fluid pt-2">    
  8.     <div class="row">    
  9.         <div class="col-md-8">    
  10.             <div class="card border-secondary">    
  11.                 <div class="card-body">    
  12.                     <h4 class="card-title">Customer Details</h4>    
  13.                     <div class="row">    
  14.                         <div class="col-md-8">    
  15.                             <div class="form-group">    
  16.                                 <label for="name">Name</label>    
  17.                                 <input type="text" class="form-control" name="name" id="name">    
  18.                             </div>    
  19.                             <div class="form-group">    
  20.                                 <label for="address">Address</label>    
  21.                                 <textarea class="form-control" name="address" id="address" row="3"></textarea>    
  22.                             </div>    
  23.                         </div>    
  24.                         <div class="col-md-4">    
  25.                             <div class="form-group">    
  26.                                 <label for="email">Email ID</label>    
  27.                                 <input type="email" class="form-control" name="email" id="email">    
  28.                             </div>    
  29.                             <div class="form-group">    
  30.                                 <label for="contactNo">Contact No.</label>    
  31.                                 <input type="number" class="form-control" name="contactNo" id="contactNo">    
  32.                             </div>    
  33.                         </div>    
  34.                     </div>    
  35.                 </div>    
  36.             </div>    
  37.             <div class="card border-secondary mt-2">    
  38.                 <div class="card-body">    
  39.                     <h4 class="card-title d-flex justify-content-between">Order Details <button type="button"    
  40.                             class="btn btn-secondary">+</button></h4>    
  41.                     <div class="row">    
  42.                         <table class="table">    
  43.                             <thead>    
  44.                                 <tr>    
  45.                                     <th width="25%">Product</th>    
  46.                                     <th width="25%">Price</th>    
  47.                                     <th width="25%">Quantity</th>    
  48.                                     <th width="25%">Amount</th>    
  49.                                 </tr>    
  50.                             </thead>    
  51.                             <tbody>    
  52.                                 <tr>    
  53.                                     <td scope="row">    
  54.                                         <input type="text" class="form-control" name="productName" id="productName">    
  55.                                     </td>    
  56.                                     <td>    
  57.                                         <input type="number" class="form-control" name="price" id="price">    
  58.                                     </td>    
  59.                                     <td>    
  60.                                         <input type="number" class="form-control" name="quantity" id="quantity">    
  61.                                     </td>    
  62.                                     <td></td>    
  63.                                 </tr>    
  64.                             </tbody>    
  65.                         </table>    
  66.                     </div>    
  67.                 </div>    
  68.             </div>    
  69.             <div class="card border-secondary mt-2">    
  70.                 <div class="card-body">    
  71.                     <h4 class="card-title">Additional Details</h4>    
  72.                     <div class="form-group">    
  73.                         <textarea class="form-control" name="additionalDetails" rows="3"></textarea>    
  74.                     </div>    
  75.                 </div>    
  76.             </div>    
  77.     
  78.         </div>    
  79.         <div class="col-md-4">    
  80.             <button type="button" name="" class="btn btn-secondary btn-lg btn-block">Download Invoice</button>    
  81.             <button type="button" name="" class="btn btn-secondary btn-lg btn-block">Print Invoice</button>    
  82.             <button type="button" name="" class="btn btn-secondary btn-lg btn-block">Open Invoice</button>    
  83.         </div>    
  84.     </div>    
  85. </div>  
Invoice Generator UI

Get Invoice Details in Component and Add the Click events for Action Buttons

 
We will create an invoice object in AppComponent and bind it with invoice form using two-way data binding. We will add addProduct() method to add product in invoice and update generatePdf() method to get action argument and execute the related pdfMake method.
  1. /*** app.component.ts  ***/    
  2.     
  3. // ...    
  4.     
  5. class Product{    
  6.   name: string;    
  7.   price: number;    
  8.   qty: number;    
  9. }    
  10. class Invoice{    
  11.   customerName: string;    
  12.   address: string;    
  13.   contactNo: number;    
  14.   email: string;    
  15.       
  16.   products: Product[] = [];    
  17.   additionalDetails: string;    
  18.     
  19.   constructor(){    
  20.     // Initially one empty product row we will show     
  21.     this.products.push(new Product());    
  22.   }    
  23. }    
  24. @Component({    
  25.   selector: 'app-root',    
  26.   templateUrl: './app.component.html',    
  27.   styleUrls: ['./app.component.css']    
  28. })    
  29. export class AppComponent {    
  30.   invoice = new Invoice();     
  31.       
  32.   generatePDF(action = 'open') {    
  33.         
  34.     let docDefinition = {      
  35.         header: 'C#Corner PDF Header',      
  36.         content: 'Sample PDF generated with Angular and PDFMake for C#Corner Blog'      
  37.       };    
  38.     
  39.     if(action==='download'){    
  40.       pdfMake.createPdf(docDefinition).download();    
  41.     }else if(action === 'print'){    
  42.       pdfMake.createPdf(docDefinition).print();          
  43.     }else{    
  44.       pdfMake.createPdf(docDefinition).open();          
  45.     }    
  46.     
  47.   }    
  48.     
  49.   addProduct(){    
  50.     this.invoice.products.push(new Product());    
  51.   }    
  52.       
  53. }   
Now let’s configure the document definition object to generate the PDF in the required layout and format. 
 

Show Invoice Header with Custom Styling

 
We will update docDefinition object in generatePDF() method as below to show Invoice Header. To add multiple lines in PDF, we can use the content property of the document definition object as an array form, as shown below. We have also added some styling here. 
  1. let docDefinition = {  
  2.     content: [  
  3.       {  
  4.         text: 'ELECTRONIC SHOP',  
  5.         fontSize: 16,  
  6.         alignment: 'center',  
  7.         color: '#047886'  
  8.       },  
  9.       {  
  10.         text: 'INVOICE',  
  11.         fontSize: 20,  
  12.         bold: true,  
  13.         alignment: 'center',  
  14.         decoration: 'underline',  
  15.         color: 'skyblue'  
  16.       }  
  17.     }  

Add Section Header and Common Style

 
The way we write common CSS with .class in CSS file, and apply it at multiple places on HTML file, in the same way pdfMake allows us to create common styles, which we can use on multiple lines. For example, we will create here a section header line and create a common style for the same. 
  1. let docDefinition = {  
  2.     content: [  
  3.         // Previous configuration  
  4.         {  
  5.             text: 'Customer Details',  
  6.             style: 'sectionHeader'  
  7.         }  
  8.     ],  
  9.     styles: {  
  10.         sectionHeader: {  
  11.             bold: true,  
  12.             decoration: 'underline',  
  13.             fontSize: 14,  
  14.             margin: [0, 15, 0, 15]  
  15.         }  
  16.     }  
  17. }  
 As you can see here, we have created a common style in styles property of document definition object and used it on customer details line with the style property.
 

Add Columns in PDF

 
We can add columns in pdf with columns property of PDFMake as shown below. For this application we will create two columns, in one column we will show customer details and in another column, we will show the current date and random bill number.
  1. let docDefinition = {  
  2.     content: [  
  3.         // Previous configuration  
  4.         {  
  5.             columns: [  
  6.                 [  
  7.                     {  
  8.                         text: this.invoice.customerName,  
  9.                         bold: true  
  10.                     },  
  11.                     { text: this.invoice.address },  
  12.                     { text: this.invoice.email },  
  13.                     { text: this.invoice.contactNo }  
  14.                 ],  
  15.                 [  
  16.                     {  
  17.                         text: `Date: ${new Date().toLocaleString()}`,  
  18.                         alignment: 'right'  
  19.                     },  
  20.                     {  
  21.                         text: `Bill No : ${((Math.random() * 1000).toFixed(0))}`,  
  22.                         alignment: 'right'  
  23.                     }  
  24.                 ]  
  25.             ]  
  26.         },  
  27.     ],  
  28.     // Common Styles  
  29. }  

Add Table in PDF

 
We can create a table in PDF with table property of document definition object.. We will show order products in table form as shown below :
  1. let docDefinition = {  
  2.     content: [  
  3.         // Previous configuration  
  4.         {  
  5.             text: 'Order Details',  
  6.             style: 'sectionHeader'  
  7.         },  
  8.         {  
  9.             table: {  
  10.                 headerRows: 1,  
  11.                 widths: ['*''auto''auto''auto'],  
  12.                 body: [  
  13.                     ['Product''Price''Quantity''Amount'],  
  14.                     ...this.invoice.products.map(p => ([p.name, p.price, p.qty, (p.price * p.qty).toFixed(2)])),  
  15.                     [{ text: 'Total Amount', colSpan: 3 }, {}, {}, this.invoice.products.reduce((sum, p) => sum + (p.qty * p.price), 0).toFixed(2)]  
  16.                 ]  
  17.             }  
  18.         }  
  19.     ],  
  20.     // Common Styles  
  21. }  
 Table property has the following properties
  • headerRows: this property specifies the no. of starting rows of the body is header row. Header rows will be repeated when a table is continued on the second page.
  • widths: using this property we can assign the width for each column. we can use *, auto, and fixed number as width.
  • body: this property contains the list of rows in array form. where each inner array represents the cell array of that row.

Add QR Code in PDF

 
We can add the QR Code in a row with qr property as shown below, In our application, QR Code will be generated from customerName.
  1. let docDefinition = {  
  2.     content: [  
  3.         // Previous Configuration  
  4.         {  
  5.             columns: [  
  6.                 [{ qr: `${this.invoice.customerName}`, fit: '50' }],  
  7.                 [{ text: 'Signature', alignment: 'right', italics: true }],  
  8.             ]  
  9.         },  
  10.     ],  
  11.     // Common Styles  
  12. }   

Add List in PDF

 
We can add the unordered and ordered list in PDF with ul and ol property of PDFMake document definition object. We will create terms and conditions list as below,
  1. let docDefinition = {  
  2.     content: [  
  3.         // Previous Configuration  
  4.         {  
  5.             ul: [  
  6.               'Order can be return in max 10 days.',  
  7.               'Warrenty of the product will be subject to the manufacturer terms and conditions.',  
  8.               'This is system generated invoice.',  
  9.             ],  
  10.         }  
  11.     ],  
  12.     // Common Styles  
  13. }  
!!! Great  We are done with Invoice Generator Implementation.
 
Final Source Code
 
Check out the final source code: Angular PDFMake Invoice Generator Repository
 
If you feel this application is useful to you, give us a  on GitHub.
 
Live Invoice Generator Application
 
Check out the live running application: Angular PDFMake Invoice Generator
 
Final Output
 
Invoice Generator Application : Client Side PDF generation in Angular with PDFMake
 

Summary

 
In this article, we have discussed the various approaches to generate a PDF in an application. We have implemented Invoice Generator application to demonstrate client-side pdf generation in angular with pdfmake.
 
I hope you like this article. Give your valuable feedback and suggestions in the below comment section.