My experience on my daily works... helping others ease each other

Friday, August 31, 2018

Downloading and Formatting data for PDF output using Ionic, Angular, Cordova and TypeScript

It has been a while I did not focus and wrote anything on this blog and it is good to be back on track.

Lets kick start with writing PDF on your mobile apps. You may have data retrieve and your client require you to download the data as PDF. I've done that on Excel and it was way easy to do that.

Now lets start for PDF. It is pretty much easy too. We are going to use PDFMaker library.

If you follow the steps shows here, it shall be sufficient.

https://ionicacademy.com/create-pdf-files-ionic-pdfmake/

and you can read the entire library here

http://pdfmake.org/#/gettingstarted

You need to download and install three libraries for it to work
# Install Cordova Plugins
1. ionic cordova plugin add cordova-plugin-file-opener2
2. ionic cordova plugin add cordova-plugin-file

#Install NPM packages
3. npm install pdfmake @ionic-native/file-opener @ionic-native/file
Once complete, declare it in your apps.module.ts. The link above shall guide you with the sample.

The link above shows how it was done in a single page.  I, on the other hand, create a service provider to ease me in sharing the service between the apps. Below is the snapshot of my code... and Yup, I'm using Promise to ensure I can control the outcome and catch any error.

#the import
import { Platform } from 'ionic-angular';
//import { Http } from '@angular/http';
import { Injectable, Component } from '@angular/core';

import pdfMake from 'pdfmake/build/pdfmake';
import pdfFonts from 'pdfmake/build/vfs_fonts';
pdfMake.vfs = pdfFonts.pdfMake.vfs;

import { File } from '@ionic-native/file';
import { FileOpener } from '@ionic-native/file-opener';

#the control
createPdf( isMin: boolean ): Promise<any>{
return new Promise ((resolve,reject) => {
if( isMin ){
this.createPdfMin()
.then((data) => {
return resolve( data );
})
.catch( (error) => {
return reject( error );
})
} else {
this.createPdfMax()
.then((data) => {
return resolve( data );
})
.catch( (error) => {
return reject( error );
})
}
})
} //end createPdf

#partial code to create pdf
createPdfMin(): Promise<any>{
//let docDefinition = null;

return new Promise((resolve) => {
let docDefinition = {
// a string or { width: number, height: number }
pageSize: 'A4',

// by default we use portrait, you can change it to landscape if you wish
pageOrientation: 'potrait',

// [left, top, right, bottom] or [horizontal, vertical] or just a number for equal margins
pageMargins: [ 10, 30, 10, 30 ],

content: [
{ text: 'The Header', style: 'header' },
{ text: new Date().toTimeString(), alignment: 'right' },
//SPA Section
{ text: 'Sub Header', style: 'subheader' },

{ text: 'Sub Sub Header', style: 'subheader2' },
{
columns: [
{
text: 'Intial data'
},
{
width: '*',
text: theValue.toLocaleString('en-US', {
style: 'currency',
currency: 'MYR',
})
}
],
// optional space between columns
columnGap: 10
},
{ text: '---------------------------------------------------', style: 'subheader2' },
],
styles: {
header: {
fontSize: 18,
bold: true,
},
subheader: {
fontSize: 14,
bold: true,
margin: [0, 15, 0, 0]
},
subheader2: {
fontSize: 12,
bold: true,
margin: [0, 15, 0, 0]
},
story: {
italic: true,
alignment: 'center',
width: '50%',
}
}
}

this.pdfObj = pdfMake.createPdf(docDefinition);

return resolve( this.pdfObj );
});
} //end createPdfMin

#code to download the pdf
downloadPdf(pdfObj, type:string):Promise<any>{
console.log('fileCreator.downloadPdf()');
return new Promise((resolve) => {
if (this.plt.is('cordova')) {
pdfObj.getBuffer((buffer) => {
var blob = new Blob([buffer], { type: 'application/pdf' });
// Save the PDF to the data Directory of our App
this.file.writeFile(this.file.dataDirectory, 'file_' + type + '.pdf', blob, { replace: true }).then(fileEntry => {
// Open the PDf with the correct OS tools
this.fileOpener.open(this.file.dataDirectory + 'file_' + type + '.pdf', 'application/pdf');
})
});
} else {
// On a browser simply use download!
this.pdfObj.download();
}
return resolve("success");
})
} //end function downloadPdf

#how it is called from other page or file
this.fileCreatorProvider.createPdf(true)
.then((data) =>{
//download the file for min
this.fileCreatorProvider.downloadPdf(data,'type')
.then((data) => {
if ( data === 'success'){
this.presentAlert('Download Complete','Successfully download the file','success');
} else {
this.presentAlert('Download Error','Fail to download the file','error');
}
})
.catch((error) => {
this.presentAlert('Download Error','Fail to download the file. Catch ' + error,'error');
})
})
.catch((error) => {
this.presentAlert('Download Error','Fail to download the file. Catch ' + error,'error');
})


and you shall be ready.

By the way, it is just snapshot. It shall give you brief idea on how to do that.

Happy Coding!!!


Share:

0 comments:

About Me

Somewhere, Selangor, Malaysia
An IT by profession, a beginner in photography

Blog Archive

Blogger templates