Ionic | Working with jsPDF

Introduction

The javascript library jsPDF, is a Client-side JavaScript PDF generation for everyone.

With a npm-Module, you can integrate this functionality into your Ionic App.

This Git Repository with the code for this blog is here.

Preparation

Create your empty app

❯ mkdir Ionic_Working-with_jsPDF
❯ cd Ionic_Working-with_jsPDF
❯ ionic start app sidemenu  --type angular
√ Preparing directory .app in 2.63ms
√ Downloading and extracting sidemenu starter in 665.67ms
? Integrate your new app with Capacitor to target native iOS and Android? No
❯ cd app

Install npm Module

❯ npm install        jspdf
❯ npm install @types/jspdf

oder

❯ yarn add        jspdf
❯ yarn add @types/jspdf

Start Editor and serve your app

❯ vscode .
❯ ionic serve

Add new Page for PDF functionality

Create new Page

❯ ionic generate page pages/PDF

Add page to sidemenu

Edit app.components.ts

public appPages = [
	{	title: 'PDF',	url: '/pdf',		icon: print'	},
	{	title: 'Inbox',	url: '/folder/Inbox',	icon: 'mail',	},

Add jsPDF functionality

Add jspfs reference to pages/pdf/pdf.page.ts

import { jsPDF } from 'jspdf';

Create a function for converting to PDF

public downloadPDF() {
	var data = document.getElementById('printcontent') as HTMLElement;

	let pdf = new jsPDF('p', 'mm', 'a4');

	pdf.html(data, {
		callback: (pdf) => {pdf.output('dataurlnewwindow');}
	});
}

Add download button

Change pages/pdf/pdfhtml

<div>
	<input type="button" value="Convert" (click)="downloadPDF()" />
</div>

Summary

A lot more examples could be found in my repository. Just create a starter app with this template and begin to play

DeutschEnglishFrançaisहिन्दी