How To Export PDF and View with Ionic 4 & Angular
[ad_1]
Another step by step guide working on IONIC4 + ANGULAR + CORDOVA how to export then view as PDF file using (DOM to IMAGE) with JSPDF / File Opener. This example can be implemented working on paperless projects for example if you have an app that the functionality is you don’t want to use a printer to see the reports generated from your app. the user can press a button then it will generate a PDF file then share to any apps like Facebook, Watsup, email, etc.
Requirements for this implementation
- Updates Node.js
- IONIC 4
- Cordova / Capacitor
1 2 3 4 5 6 7 8 9 10 |
node -v v10.14.2 npm -v 6.4.1 ionic -v ionic 4.12.0 > to run an update <strong>npm i -g ionic</strong> cordova -v cordova 8.1.2 > to run an update type <strong>npm i -g cordova</strong> |
Generating a New Project Files
To generate a new project with ionic 4 & angular just type the command below.
1 |
ionic start ionic-prod-pdf blank --type=angular |
Then there will be a question coming out from your screen during the installation, you just press N for no. then open the newly created project app folder. “ionic-prod-pdf”
1 |
cd ./ionic-prod-pdf |
Finalizing the project file to check if you successfully configure your working environment, you need to run the Ionic project to make it sure your configuration is working fine just type the command below. note: execute this command inside of your project directory.
1 |
> ionic serve -l |
Press Y to install (@ionic/lab) then the app preview will show on your screen.
Installing the DOM-To-IMAGE – jSPDF and File Opener
To use DOM-to-IMAGE javascript library type the following command below.
1 2 |
> npm install dom-to-image --save > npm install @types/dom-to-image --save |
To install the jSPDF Javascript library, just follow and type the list of command below.
1 2 |
> npm install jspdf --save > npm install @types/jspdf --save |
The dom-to-image and the jSPDF javascript library are installed and ready to use. now next is you need to install the Ionic 4 Native File Opener component just follow the command below
1 2 3 4 |
> ionic cordova plugin add cordova-plugin-file-opener2 > npm install --save @ionic-native/[email protected] > ionic cordova plugin add cordova-plugin-file > npm install --save @ionic-native/[email protected] |
Open your file explorer and navigate the src/app/app.module.ts and add this @ionic-native/file-opener/ngx
module.
1 |
import FileOpener from '@ionic-native/file-opener/ngx'; |
Add that module to @NgModule
providers.
Next is add the FileOpener @NgModule base code providers:[]
1 2 3 4 5 6 |
providers: [ Â StatusBar, Â SplashScreen, Â FileOpener, Â provide: RouteReuseStrategy, useClass: IonicRouteStrategy ], |
3. The Ionic HTML page for the page template
As our goal, we need to generate a page that can be printable and exportable to PDF format. now open your src/app/home/home.page.html and remove all code inside of the html file page and copy all the HTML tags below and phase to the src/app/home/home.page.html.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 |
<ion-header> Â <ion-toolbar> Â Â <ion-title> I N V O I C E </ion-title> Â Â <ion-buttons slot="primary"> Â Â Â <ion-button color="primary" (click)="exportPdf()"> Â Â Â Â <ion-icon slot="icon-only" name="print"></ion-icon> Â Â Â </ion-button> Â Â </ion-buttons> Â </ion-toolbar> </ion-header> <ion-content padding> Â <div class="printable-content"> Â Â <div class="printable-area" id="printable-area"> Â Â Â <table class="header-table"> Â Â Â Â <tr> Â Â Â Â Â <td width="40%" class="title"><img src="<a href="https://www.14core.com/wp-content/uploads/2019/05/logo-14core-1.jpg">https://www.14core.com/wp-content/uploads/2019/05/logo-14core-1.jpg</a>" alt="14CORE LOGO" height="40px" /></td> Â Â Â Â Â <td width="60%"> Â Â Â Â Â Â <table width="100%"> Â Â Â Â Â Â Â <tr> Â Â Â Â Â Â Â Â <td width="50%">009878825452</td> Â Â Â Â Â Â Â Â <td width="50%">Your Address 1st</td> Â Â Â Â Â Â Â </tr> Â Â Â Â Â Â Â <tr> Â Â Â Â Â Â Â Â <td>[email protected]</td> Â Â Â Â Â Â Â Â <td>City, State, Country</td> Â Â Â Â Â Â Â </tr> Â Â Â Â Â Â Â <tr> Â Â Â Â Â Â Â Â <td>14core.com</td> Â Â Â Â Â Â Â Â <td>Post Code</td> Â Â Â Â Â Â Â </tr> Â Â Â Â Â Â </table> Â Â Â Â Â </td> Â Â Â Â </tr> Â Â Â </table> Â Â Â <h1>Invoice</h1> Â Â Â <table class="subheader-table"> Â Â Â Â <tr> Â Â Â Â Â <td width="30%"> Â Â Â Â Â Â <dt>Billed To:</dt> Â Â Â Â Â Â <dd>Client Name</dd> Â Â Â Â Â Â <dd>Address 1st Line</dd> Â Â Â Â Â Â <dd>City, State, Country</dd> Â Â Â Â Â Â <dd>Post Code</dd> Â Â Â Â Â </td> Â Â Â Â Â <td width="30%"> Â Â Â Â Â Â <dt>Invoice Number:</dt> Â Â Â Â Â Â <dd>009223-222</dd> Â Â Â Â Â </td> Â Â Â Â Â <td width="40%"> Â Â Â Â Â Â <dt>Invoice Total:</dt> Â Â Â Â Â Â <dd>$6.600</dd> Â Â Â Â Â </td> Â Â Â Â </tr> Â Â Â </table> Â Â Â <h3>Invoice Details</h3> Â Â Â <table class="detail-table"> Â Â Â Â <tr> Â Â Â Â Â <th width="50%">Description</th> Â Â Â Â Â <th width="20%">Unit Price</th> Â Â Â Â Â <th width="10%">Qty</th> Â Â Â Â Â <th width="20%">Amount</th> Â Â Â Â </tr> Â Â Â Â <tr> Â Â Â Â Â <td>Metal Plavor Pizza Pie</td> Â Â Â Â Â <td>$4.500</td> Â Â Â Â Â <td>1</td> Â Â Â Â Â <td>$4.500</td> Â Â Â Â </tr> Â Â Â Â <tr> Â Â Â Â Â <td>Fresh Dirt Juice</td> Â Â Â Â Â <td>$500</td> Â Â Â Â Â <td>1</td> Â Â Â Â Â <td>$500</td> Â Â Â Â </tr> Â Â Â Â <tr> Â Â Â Â Â <td>Grilled Stone Burger</td> Â Â Â Â Â <td>$1.000</td> Â Â Â Â Â <td>1</td> Â Â Â Â Â <td>$1.000</td> Â Â Â Â </tr> Â Â Â </table> Â Â Â <table class="footer-table"> Â Â Â Â <tr> Â Â Â Â Â <td width="80%">Sub Total: </td> Â Â Â Â Â <td width="20%">$6.000</td> Â Â Â Â </tr> Â Â Â Â <tr> Â Â Â Â Â <td>Tax: </td> Â Â Â Â Â <td>$600</td> Â Â Â Â </tr> Â Â Â </table> Â Â </div> Â </div> </ion-content> |
Open your src/app/home/home.page.css and copy all the CSS / SASS element to your src/app/home/home.page.css
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 |
ion-content {  background-color: #c0c0ff;  .printable-content {   margin: 16px;   overflow-x: scroll;   overflow-y: scroll;   background-color: #ffffff;   .printable-area    width: 595px;    height: 540px;    .header-table     background-color: #18AC52;     margin: 2%;     width: 96%;     color: #ffffff;     th, td      text-align: left;      padding: 5px;         .title      padding: 5px 20px;      font-size: 20px;      font-weight: bold;      text-transform: uppercase;           h1, h3     margin-left: 10px;       h3     margin-top: 20px;       .subheader-table     margin: 2%;     width: 96%;     td      vertical-align: top;      dt       font-size: 11px;       color: #999;       margin-bottom: 5px;           dd       margin: 0;              td:last-child      text-align: right;      dd       font-size: 28px;       font-weight: bold;                .detail-table     margin: 2%;     width: 96%;     border-top: 2px solid #CCC;     border-bottom: 2px solid #CCC;     th, td      padding: 5px;         th      border-bottom: 2px solid #CCC;         td:nth-child(2), td:nth-child(4)      text-align: right;         td:nth-child(3)      text-align: center;           .footer-table     margin: 2%;     width: 96%;     td      padding: 5px;      text-align: right;      font-weight: bold;           } } |
4. How to Export to PDF and Preview the Page
This step is to export the page to PDF file and preview using file opener. goto src/app/home/home.page.ts and edit the home.page.ts then add this library to your ts file. Inject listed imports below to the constructor.
1 2 3 4 5 |
> import LoadingController from '@ionic/angular'; > import * as jsPDF from 'jspdf'; > import domtoimage from 'dom-to-image'; > import File, IWriteOptions from '@ionic-native/file/ngx'; > import FileOpener from '@ionic-native/file-opener/ngx'; |
Add a list code below variables for the use of the loading controller before the constructor.
1 2 3 4 |
constructor(public loadingCtrl: LoadingController, Â private file: File, Â private fileOpener: FileOpener) |
1 |
loading: any; |
Add a function for presenting the loading controller below the constructor.
1 2 3 4 5 6 |
async presentLoading(msg)  const loading = await this.loadingController.create(   message: msg  );  return await loading.present(); |
The code below is the typescript function that export and view the pdf file format.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 |
exportPdf()  this.presentLoading('Creating PDF file...');  const div = document.getElementById("printable-area");  const options = background: "white", height: div.clientWidth, width: div.clientHeight ;  domtoimage.toPng(div, options).then((dataUrl)=>   //Initialize JSPDF   var doc = new jsPDF("p","mm","a4");   //Add image Url to PDF   doc.addImage(dataUrl, 'PNG', 20, 20, 240, 180);   let pdfOutput = doc.output();   // ArrayBuffer will allow you to put image inside PDF   let buffer = new ArrayBuffer(pdfOutput.length);   let array = new Uint8Array(buffer);   for (var i = 0; i < pdfOutput.length; i++)     array[i] = pdfOutput.charCodeAt(i);     //PDF file will stored , you can change this line as you like   // for more information please visit https://ionicframework.com/docs/native/file/   const directory = this.file.dataDirectory ;   const fileName = "invoice.pdf";   let options: IWriteOptions = replace: true ;   this.file.checkFile(directory, fileName).then((success)=>    //Writing File to Device    this.file.writeFile(directory,fileName,buffer, options)    .then((success)=>     this.loading.dismiss();     console.log("File created Succesfully" + JSON.stringify(success));     this.fileOpener.open(this.file.dataDirectory + fileName, 'application/pdf')      .then(() => console.log('File is opened'))      .catch(e => console.log('Error opening file', e));    )    .catch((error)=>     this.loading.dismiss();     console.log("Cannot Create File " +JSON.stringify(error));    );   )   .catch((error)=>    //Writing File to Device    this.file.writeFile(directory,fileName,buffer)    .then((success)=>     this.loading.dismiss();     console.log("File created Succesfully" + JSON.stringify(success));     this.fileOpener.open(this.file.dataDirectory + fileName, 'application/pdf')      .then(() => console.log('File is opened'))      .catch(e => console.log('Error opening file', e));    )    .catch((error)=>     this.loading.dismiss();     console.log("Cannot Create File " +JSON.stringify(error));    );   );  )  .catch(function (error)   this.loading.dismiss();   console.error('oops, something went wrong!', error);  ); |
Testing the IONIC app on our Virtual Device
Because we are using the Native plugin of Ionic 4 and Cordova, we should run on Device of Simulator to make the plugin working. Type this command to add Cordova platform.
Note: before we going to test the app in the Device Simulator it requires to generate a compatibility format so that, all required plugin will work without issues. just type the command below. if you wat to test it with iOS type > ionic cordova platform add ios
and if you want to test it with Android ionic cordova platform add android
1 2 |
> ionic cordova platform add ios > ionic cordova platform add android |
If you want to run the app directly to android or device jute enter the following command below.
1 2 |
> ionic cordova run ios > ionic cordova run android |
In my case, I’ve got this error when running on the Android device.
If you encounter an error like ” Failed to execute aapt” or Build failed with an exception, just open ( platform/android/project.properties ) then change the cordova.system.library.1=com.android.support:support-v4:+
cordova.system.library.2=com.android.support:support-annotations:27+
to :
1 2 |
cordova.system.library.1=com.android.support:support-v4:27.1.0 cordova.system.library.2=com.android.support:support-annotations:27.1.0 |
You should see this page when it’s running successfully.
[ad_2]