Ionic: How to create PDF file with PdfMake(step-by-step)

Rakesh Sahu
6 min readJan 10, 2018

--

Ionic is a hybrid platform that helps to create native mobile apps with JavaScript. In this article, we are going to learn how to create a PDF in Ionic.

PdfMake is an open source JavaScript library to generate PDF in browser or mobile device. It provides custom layout options for your document and also allows you to add images. We start by creating an app called PdfCreatorApp to generate a PDF file for us and save in device memory .

Download and install node which is bundled with npm so you should see a version of npm. npm is a package manager for JavaScript which helps you to manage all your dependencies.

After installing, run node -v in command line. You should see a version higher than v 8.9.1.

Next, run npm -v in command line. If you see a version lower than 5.6.0, you should update.

Run npm install npm@latest -g to which installs the latest stable version of npm.

Install ionic and Cordova by running npm install -g cordova ionic in command line(the -g command makes a module available globally).

Create a blank ionic app by running ionic start PdfCreatorApp in command line.

Next, install PdfMake library by running command npm install pdfmake — — save.

Copy all content from node_modules>pdfmake>build to src>www>pdfmake>build.(Note: You have to create missing folders).

Go to your project directory. It should look this this.

We will make a button to execute the action of creating a PDF file and save it in device memory.

Creating the View

Edit the home.html file in src>pages>home to add a button on the screen.

<ion-header><ion-navbar><ion-title>Pdf Creator</ion-title></ion-navbar></ion-header><ion-content padding><div id="wrapper"><button ion-button (click)='makePdf()' >Generate PDF</button></div></ion-content>

You can add styling to the button to bring it to center of screen.

page-home {#wrapper{height: 100%;display: flex;align-items: center;justify-content: center;}}

Creating the Controller

Edit the home.ts file in src>pages>home to add makePdf() function which will generate and display the PDF in browser window.

import { File } from '@ionic-native/file';import { Component } from '@angular/core';import * as pdfmake from 'pdfmake/build/pdfmake';import * as pdfFonts from 'pdfmake/build/vfs_fonts';import { NavController } from 'ionic-angular';@Component({selector: 'page-home',templateUrl: 'home.html'})export class HomePage {constructor(public navCtrl: NavController, public file: File) {}makePdf() {pdfmake.vfs = pdfFonts.pdfMake.vfs;var docDefinition = {content: [{columns: [{image: 'data:image/jpeg;base64,your_image_here',fit: [100, 100]},[{ text: 'BITCOIN', style: 'header' },{ text: 'Cryptocurrency Payment System', style: 'sub_header' },{ text: 'WEBSITE: https://bitcoin.org/', style: 'url' },]]}],styles: {header: {bold: true,fontSize: 20,alignment: 'right'},sub_header: {fontSize: 18,alignment: 'right'},url: {fontSize: 16,alignment: 'right'}},pageSize: 'A4',pageOrientation: 'portrait'};pdfmake.createPdf(docDefinition).open();}}

Import pdfmake and pdfFonts which are the required libraries. I have added an image in base64 format. You can generate base64 code for any image by following this link. PdfMake provides different formatting options to structure and style the document. You can try all options by following this link. You can open the PDF in browser window by calling open() on the document created.

Running in browser

Run ionic serve on command line.

Open your browser (Chrome is nice!) , type localhost:8100, and press enter. Switch to developer mode and choose any device. You should see your app on mobile screen (just like a emulator).

You can see the button placed in middle of screen. Click on the button to open the PDF in a new browser window.

This is how you create and display PDF on browser window.

Running on Android device

Now we try to save the PDF in device memory. Open home.ts and edit the code to add the following

import { File } from '@ionic-native/file';import { Component } from '@angular/core';import * as pdfmake from 'pdfmake/build/pdfmake';import * as pdfFonts from 'pdfmake/build/vfs_fonts';import { NavController, ToastController } from 'ionic-angular';@Component({selector: 'page-home',templateUrl: 'home.html'})export class HomePage {constructor(public navCtrl: NavController, public file: File, public toastCtrl: ToastController) {}
makePdf() {let self = this;pdfmake.vfs = pdfFonts.pdfMake.vfs;var docDefinition = {content: [{columns: [{
  • image: 'data:image/jpeg;base64,your_image_here ,
  • fit: [100, 100]
},[{ text: 'BITCOIN', style: 'header' },{ text: 'Cryptocurrency Payment System', style: 'sub_header' },{ text: 'WEBSITE: https://bitcoin.org/', style: 'url' },]]}],styles: {header: {bold: true,fontSize: 20,alignment: 'right'},sub_header: {fontSize: 18,alignment: 'right'},url: {fontSize: 16,alignment: 'right'}},pageSize: 'A4',pageOrientation: 'portrait'};pdfmake.createPdf(docDefinition).getBuffer(function (buffer) {let utf8 = new Uint8Array(buffer);let binaryArray = utf8.buffer;self.saveToDevice(binaryArray,"Bitcoin.pdf")});}saveToDevice(data:any,savefile:any){let self = this;self.file.writeFile(self.file.externalDataDirectory, savefile, data, {replace:false});const toast = self.toastCtrl.create({message: 'File saved to your device',duration: 3000,position: 'top'});toast.present();}}

We will require ionic native file manager module to save the file to local memory. Install this module by running npm install @ionic-native/file. Import this module in app.module.ts

import { File } from '@ionic-native/file';import { StatusBar } from '@ionic-native/status-bar';import { ErrorHandler, NgModule } from '@angular/core';import { BrowserModule } from '@angular/platform-browser';import { SplashScreen } from '@ionic-native/splash-screen';import { IonicApp, IonicErrorHandler, IonicModule } from 'ionic-angular';import { MyApp } from './app.component';import { HomePage } from '../pages/home/home';@NgModule({declarations: [MyApp,HomePage],imports: [BrowserModule,IonicModule.forRoot(MyApp)],bootstrap: [IonicApp],entryComponents: [MyApp,HomePage],providers: [File,StatusBar,SplashScreen,{provide: ErrorHandler, useClass: IonicErrorHandler}]})export class AppModule {}

We will also require cordova file plugin to access device’s internal or external memory.Run ionic cordova plugin add cordova-plugin-file in command line to install the plugin.

To run the app on Android device, we need to add android platform in our project. Type ionic cordova platform add android in command line. This will add android platform in config.xml in project structure.Now build the android project by running ionic cordova build android.

After the build process is completed, open the folder android under platforms in project directory in Android Studio. Run the app in emulator.You can see PdfCreatorApp installing in the device. Wait till the app opens.

Click on the GENERATE PDF button. You will receive a confirmation toast File saved to your device.

Android does not provide default pdf viewer. You can install any pdf viewer from Google Play Store.

Using any File Manager, Go to your device memory and look for Documents. You will find Bitcoin.pdf file.

Open the file.

That’s how you create and save PDF file in an android device.

--

--