Ionic 6 Angular Create, Export and View PDF File Tutorial
In this thorough step-by-step example, we will explain how to create, export, and view PDF files in the Ionic 6 Angular application with the help of File, File Opener 2, jsPDF, DOM to Image, and Ionic native & Cordova File Opener plugins.
We will create a static data table, pour some dummy data into it using HTML markup; this will help us create a PDF viewer in the Ionic app, further we will show you how to create and display PDF file and also how to open the PDF file in an Ionic app.
We will certainly take the assistance of the node package manager (npm), Ionic native, and Cordova registry to add the third-party dependencies to create a PDF viewer in the Ionic ecosystem.
Let us understand about the plugins and packages we are employing in this Ionic PDF viewer tutorial.
The jsPDF is an awesome library primarily used to generate PDFs in JavaScript, and it is available through npm. Whereas, the dom-to-image is a JavaScript library that helps in converting a self-willed DOM (document object model) node into a vector (SVG) or raster (PNG or JPEG) image.
Likewise, the File Opener plugin allows you to open a file on your device file system with its default application.
Ionic Export to PDF File Example
- Step 1: Setting Up Ionic App
- Step 2: Install NPM, Ionic Native and Cordova Plugins
- Step 3: Register File, FileOpener in App Module
- Step 4: Create Static Data Table
- Step 5: Export and Display PDF File in Ionic
- Step 6: Start Ionic Angular App
Setting Up Ionic App
Ionic app development begins by installing Ionic command-line-interface on your system:
npm install -g @ionic/cli
You are ready to install a blank new Ionic Angular app:
ionic start ionic-test-app blank --type=angular
Move to app root:
cd ionic-test-app
Install NPM, Ionic Native and Cordova Plugins
Let us start installing jsPDF, DOM to Image, and Ionic native & Cordova File, File Opener and Ionic native core plugins into the Ionic app using the given recommended commands:
ionic cordova plugin add cordova-plugin-file-opener2
npm install @ionic-native/file-opener
ionic cordova plugin add cordova-plugin-file
npm install @ionic-native/file
npm i @ionic-native/core
npm install dom-to-image
npm install @types/dom-to-image
npm install jspdf
npm install @types/jspdf
Register File, FileOpener in App Module
The File and FileOpener modules have to be added into the main app module class, hence update the app.module.ts file as suggested.
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { RouteReuseStrategy } from '@angular/router';
import { IonicModule, IonicRouteStrategy } from '@ionic/angular';
import { AppComponent } from './app.component';
import { AppRoutingModule } from './app-routing.module';
// imports
import { File } from '@ionic-native/file/ngx';
import { FileOpener } from '@ionic-native/file-opener/ngx';
@NgModule({
declarations: [AppComponent],
entryComponents: [],
imports: [BrowserModule, IonicModule.forRoot(), AppRoutingModule],
providers: [
File,
FileOpener,
{
provide: RouteReuseStrategy,
useClass: IonicRouteStrategy
}
],
bootstrap: [AppComponent],
})
export class AppModule {}
You might get “Type ‘typeof jsPDF’ has no construct signatures” error, so to fix this error, you have to set the allowSyntheticDefaultImports property to true in the tsconfig.json file.
{
...
"compilerOptions": {
"allowSyntheticDefaultImports": true
},
...
...
}
Create Static Data Table
To export to PDF in Ionic, we have to create a static responsive HTML table, add user data inside it, create a button to bind the createPdf()
function with it, and display HTML into PDF view.
Place code in home.page.html file:
<ion-header>
<ion-toolbar>
<ion-title>
Ionic HTML to PDF
</ion-title>
<ion-buttons slot="primary">
<ion-button color="danger" fill="outline" (click)="createPdf()">
View PDF
</ion-button>
</ion-buttons>
</ion-toolbar>
</ion-header>
<ion-content padding>
<div class="print-pdf">
<div class="print-wrapper" id="print-wrapper">
<table>
<thead>
<tr>
<th>First Name</th>
<th>Last Name</th>
<th>Designation</th>
</tr>
</thead>
<tbody>
<tr>
<td data-column="First Name">James</td>
<td data-column="Last Name">Matman</td>
<td data-column="Job Title">Chief Sandwich Eater</td>
</tr>
<tr>
<td data-column="First Name">Andor</td>
<td data-column="Last Name">Nagy</td>
<td data-column="Job Title">Designer</td>
</tr>
<tr>
<td data-column="First Name">Tamas</td>
<td data-column="Last Name">Biro</td>
<td data-column="Job Title">Game Tester</td>
</tr>
<tr>
<td data-column="First Name">Zoli</td>
<td data-column="Last Name">Mastah</td>
<td data-column="Job Title">Developer</td>
</tr>
<tr>
<td data-column="First Name">Szabi</td>
<td data-column="Last Name">Nagy</td>
<td data-column="Job Title">Chief Sandwich Eater</td>
</tr>
</tbody>
</table>
</div>
</div>
</ion-content>
Export and Display PDF File in Ionic
Import JSPDF, domtoimage, FileOpener, File, and IWriteOptions, thereafter inject File, and FileOpener into the constructor()
method.
We will display a loader with the custom message while the PDF file is generating, the jsPDF is highly customizable, and you can check more of its properties here.
Place code in home.page.ts and save the file:
import { Component } from '@angular/core';
import JSPDF from 'jspdf';
import domtoimage from 'dom-to-image';
import { FileOpener } from '@ionic-native/file-opener/ngx';
import { File, IWriteOptions } from '@ionic-native/file/ngx';
@Component({
selector: 'app-home',
templateUrl: 'home.page.html',
styleUrls: ['home.page.scss'],
})
export class HomePage {
constructor(
private file: File,
private fileOpener: FileOpener
) { }
createPdf() {
const pdfBlock = document.getElementById("print-wrapper");
const options = {
background: "white",
height: pdfBlock.clientWidth,
width: pdfBlock.clientHeight
};
domtoimage.toPng(pdfBlock, options).then((fileUrl) => {
var doc = new JSPDF("p","mm","a4");
doc.addImage(fileUrl, 'PNG', 10, 10, 240, 180);
let docRes = doc.output();
let buffer = new ArrayBuffer(docRes.length);
let array = new Uint8Array(buffer);
for (var i = 0; i < docRes.length; i++) {
array[i] = docRes.charCodeAt(i);
}
const directory = this.file.dataDirectory;
const fileName = "user-data.pdf";
let options: IWriteOptions = {
replace: true
};
this.file.checkFile(directory, fileName).then((res)=> {
this.file.writeFile(directory, fileName,buffer, options)
.then((res)=> {
console.log("File generated" + JSON.stringify(res));
this.fileOpener.open(this.file.dataDirectory + fileName, '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,fileName,buffer).then((res)=> {
console.log("File generated" + JSON.stringify(res));
this.fileOpener.open(this.file.dataDirectory + fileName, '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);
});
}
}
Start Ionic Angular App
Testing the app on the emulator or real device is easy in Ionic; we have provided the instructions below to start the app on the emulator.
First, add the platform:
# iOS
ionic cordova platform add ios
# Android
ionic cordova platform add android
Next, create the project build:
# iOS
ionic cordova build ios
# Android
ionic cordova build android
Ultimately, start the application:
# iOS
ionic cordova run ios -l
# Android
ionic cordova run android -l
Conclusion
PDF or Portable Document Format is a popular file format exclusively used for sharing electronic documents such as images, invoices, forms, and other essentials data.
This tutorial described how to create convert HTML markup into PDF File, export HTML to PDF File view using jsPDF, File Opener, and dom-to-image plugins. We believe you have liked our intensive efforts to enhance your knowledge in Ionic development.