Ionic Angular PDF tutorial; Throughout this extensive guide, you will learn how to export and view PDF files in the Ionic Angular app using Third-party Ionic Native, NPM and Cordova plugins.
This quick tutorial starts with creating a new Ionic project, installing and configuring ionic native, npm and Cordova packages, creating an HTML structure that we will use to export, create, and view PDF files.
Apart from that, to show and export HTML data in Ionic, we will take the help of file-opener, file, dom-to-image, and jspdf packages.
file-opener: The file-opener plugin is available through the Ionic native and Cordova repository; it helps you open a file on your device file system with its default application.
file: This package offers methods to access files and directories, not just that the File API allows read/write access to files dwelling on the device.
dom-to-image: This library is available through the node package manager; it lets you convert the DOM node into an SVG vector and raster PNG or JPEG image file.
jspdf: A special JavaScript-based package that helps you generate PDFs in JavaScript.
Ionic 6 Export and View PDF File Example
- Step 1: Install Ionic Project
- Step 2: Install File, jsPDF, dom-to-image, and File Opener 2, Core Plugins
- Step 3: Update File Dependencies in AppModule
- Step 4: Update HTML Template
- Step 5: View and Export PDF File
- Step 6: Run Ionic App
Install Ionic Project
Ionic development starts with Ionic CLI, execute the suggested command to install the latest version of Ionic CLI:
npm install -g @ionic/cli
Next, install a new Ionic Angular project:
ionic start pdf-demo-app blank --type=angular
Get into the project folder:
cd pdf-demo-app
Remove Type Errors
You have to remove strict type errors make sure to set “strictTemplates”: false
in angularCompilerOptions in tsconfig.json file.
Install File, jsPDF, dom-to-image, and File Opener 2, Core Plugins
In this step, we need to install a couple of plugins to convert HTML to PDF in Ionic app.
ionic cordova plugin add cordova-plugin-file
npm install @ionic-native/file
ionic cordova plugin add cordova-plugin-file-opener2
npm install @ionic-native/file-opener
npm install dom-to-image
npm install @types/dom-to-image
npm install jspdf
npm install @types/jspdf
npm i @ionic-native/core
The jsPDF plugin may throw “Type ‘typeof jsPDF’ has no construct signatures” error.
Fret not, it can be fixed by adding the allowSyntheticDefaultImports
property into the tsconfig.json file.
{
...
"compilerOptions": {
"allowSyntheticDefaultImports": true
},
...
...
}
Update File and FileOpener Dependencies in AppModule
This explains how to add The File and FileOpener File and FileOpener plugins in AppModule class, so open and add the given below code app.module.ts file:
...
...
import { File } from '@ionic-native/file/ngx';
import { FileOpener } from '@ionic-native/file-opener/ngx';
@NgModule({
declarations: [...],
entryComponents: [],
imports: [...],
providers: [
File,
FileOpener,
{
provide: RouteReuseStrategy,
useClass: IonicRouteStrategy
}
],
bootstrap: [...],
})
export class AppModule {}
Update HTML Template
Open home.page.html file, create a simple HTML table, add Name and Email table heading, then pour some test data that we will use to export HTML Table to PDF file in Ionic.
<ion-header>
<ion-toolbar>
<ion-title>
Ionic Export HTML to PDF
</ion-title>
<ion-buttons slot="primary">
<ion-button color="success" (click)="generatePdf()">
Create PDF
</ion-button>
</ion-buttons>
</ion-toolbar>
</ion-header>
<ion-content padding>
<div class="export-pdf">
<div class="pdf-container" id="pdf-container">
<table>
<thead>
<tr>
<th>Name</th>
<th>Email</th>
</tr>
</thead>
<tbody>
<tr>
<td data-column="Name">Leanne Graham</td>
<td data-column="Email">leanne@gmail.com</td>
</tr>
<tr>
<td data-column="Name">Ervin Howell</td>
<td data-column="Email">ervin@yahoo.com</td>
</tr>
<tr>
<td data-column="Name">Clementine Bauch</td>
<td data-column="Email">clementine@hotmail.com</td>
</tr>
<tr>
<td data-column="Name">Patricia Lebsack</td>
<td data-column="Email">patricia@wwe.com</td>
</tr>
</tbody>
</table>
</div>
</div>
</ion-content>
View and Export PDF File
In the last important step, head over to home.page.ts file, here you have to add the following code in Home page TypeScript page. Import the required plugins, inject them into the constructor and write some code to generate HTML to PDF file into the Ionic, angular app.
import { Component } from '@angular/core';
import JSPDF from 'jspdf';
import { File, IWriteOptions } from '@ionic-native/file/ngx';
import { FileOpener } from '@ionic-native/file-opener/ngx';
import domtoimage from 'dom-to-image';
@Component({
selector: 'app-home',
templateUrl: 'home.page.html',
styleUrls: ['home.page.scss'],
})
export class HomePage {
constructor(
private file: File,
private fileOpener: FileOpener
) { }
generatePdf() {
const pdfEle = document.getElementById("pdf-container");
const options = {
background: "white",
height: pdfEle.clientWidth,
width: pdfEle.clientHeight
};
domtoimage.toPng(pdfEle, options).then((filePath) => {
var jsPdfDoc = new JSPDF("p","mm","a4");
jsPdfDoc.addImage(filePath, 'PNG', 12, 12, 240, 180);
let docRes = jsPdfDoc.output();
let arrayBuffer = new ArrayBuffer(docRes.length);
let uintArray = new Uint8Array(arrayBuffer);
for (var i = 0; i < docRes.length; i++) {
uintArray[i] = docRes.charCodeAt(i);
}
const directory = this.file.dataDirectory;
const pdfFile = "pdfFile.pdf";
let iWriteOptions: IWriteOptions = {
replace: true
};
this.file.checkFile(directory, pdfFile)
.then((res)=> {
this.file.writeFile(directory, pdfFile, arrayBuffer, iWriteOptions)
.then((res)=> {
console.log("File generated" + JSON.stringify(res));
this.fileOpener.open(this.file.dataDirectory + pdfFile, 'application/pdf')
.then(() => console.log('File is exported'))
.catch(e => console.log(e));
})
.catch((error)=> {
console.log(JSON.stringify(error));
});
})
.catch((error)=> {
this.file.writeFile(directory, pdfFile, arrayBuffer)
.then((res)=> {
console.log("File created" + JSON.stringify(res));
this.fileOpener.open(this.file.dataDirectory + pdfFile, 'application/pdf')
.then(() => console.log('File exported'))
.catch(e => console.log(e));
})
.catch((error)=> {
console.log(JSON.stringify(error));
});
});
})
.catch(function (error) {
console.error(error);
});
}
}
Run Ionic App
The ionic app has been eventually created, and now you need to add the platform, create the build and run the app on the real or virtual device:
# iOS
ionic cordova platform add ios
# Android
ionic cordova platform add android
# iOS
ionic cordova build ios
# Android
ionic cordova build android
# iOS
ionic cordova run ios -l
# Android
ionic cordova run android -l