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.
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.
We now have our Angular project ready with all the needed dependencies. Run the application to check if all is good!!.
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