Search code examples
ionic-frameworkionic3pdfmake

Print PDF in ionic 3


I am using PDFMake for creating the pdf with my predefined Document definition. In my old ionic 1 project, I am passing the encoded string to print function which works fine. here is the code for old ionic 1

var dd = $scope.createDocumentDefinition();
            $timeout(function () {
                var pdf = pdfMake.createPdf(dd);
                pdf.getBase64(function (encodedString) {
                    console.log(encodedString);
                    $ionicLoading.hide();
                    window.plugins.PrintPDF.print({
                        data: encodedString,
                        type: 'Data',
                        title: 'Print Document',
                        success: function () {
                            console.log('success');
                        },
                        error: function (data) {
                            data = JSON.parse(data);
                            console.log('failed: ' + data.error);
                        }
                    });
                });
            }, 1000);

Now I am upgrading my project to Ionic 3 so I tried the same thing but the output is different here is my new ionic 3 code. printer open but instead of printing as per my document definition it just prints the encoded string.

let printer_ = this.printer;
    var dd = this.createDocumentDefinition();
    var pdf = pdfMake.createPdf(dd);
    pdf.getBase64(function (_encodedString) {
      let options: PrintOptions = {
        name: 'MyDocument'
      };
      console.log(JSON.stringify(pdf));
      printer_.print(_encodedString, options).then((msg)=>{
        console.log("Success",msg);
      },(error)  => {
        console.log("Error", error);
      });
  });

Any idea how to use this in ionic 3 ??


Solution

  • You can use pdfmake for generate PDF using ionic.

    First you need to install plugin for file and file opener.

    ionic cordova plugin add cordova-plugin-file-opener2
    ionic cordova plugin add cordova-plugin-file
    

    After that install NPM package of file, FileOpener and PDF make

    npm install pdfmake 
    npm install @ionic-native/file-opener 
    npm install @ionic-native/file
    

    Open your src/app.module.ts and include file and fileoperner reference:

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

    Add File and FileOpener in provider

    providers: [
        StatusBar,
        SplashScreen,
        {provide: ErrorHandler, useClass: IonicErrorHandler},
        File,
        FileOpener
      ]
    

    I am generating a template UI looks like this:

    <ion-header>
      <ion-navbar>
        <ion-title>
          Ionic PDF
        </ion-title>
      </ion-navbar>
    </ion-header>
    
    <ion-content padding>
    
      <ion-item>
        <ion-label stacked>From</ion-label>
        <ion-input [(ngModel)]="letterObj.from"></ion-input>
      </ion-item>
      <ion-item>
        <ion-label stacked>To</ion-label>
        <ion-input [(ngModel)]="letterObj.to"></ion-input>
      </ion-item>
      <ion-item>
        <ion-label stacked>Text</ion-label>
        <ion-textarea [(ngModel)]="letterObj.text" rows="10"></ion-textarea>
      </ion-item>
    
      <button ion-button full (click)="createPdf()">Create PDF</button>
      <button ion-button full (click)="downloadPdf()" color="secondary" [disabled]="!pdfObj">Download PDF</button>
    
    </ion-content>
    

    After that your home.component.ts code looks like this:

    import { Component } from '@angular/core';
    import { NavController, Platform } from 'ionic-angular';
    
    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';
    
    @Component({
      selector: 'page-home',
      templateUrl: 'home.html'
    })
    export class HomePage {
      letterObj = {
        to: '',
        from: '',
        text: ''
      }
    
      pdfObj = null;
    
      constructor(public navCtrl: NavController, private plt: Platform, private file: File, private fileOpener: FileOpener) { }
    
      createPdf() {
        var docDefinition = {
          content: [
            { text: 'REMINDER', style: 'header' },
            { text: new Date().toTimeString(), alignment: 'right' },
    
            { text: 'From', style: 'subheader' },
            { text: this.letterObj.from },
    
            { text: 'To', style: 'subheader' },
            this.letterObj.to,
    
            { text: this.letterObj.text, style: 'story', margin: [0, 20, 0, 20] },
    
            {
              ul: [
                'Bacon',
                'Rips',
                'BBQ',
              ]
            }
          ],
          styles: {
            header: {
              fontSize: 18,
              bold: true,
            },
            subheader: {
              fontSize: 14,
              bold: true,
              margin: [0, 15, 0, 0]
            },
            story: {
              italic: true,
              alignment: 'center',
              width: '50%',
            }
          }
        }
        this.pdfObj = pdfMake.createPdf(docDefinition);
      }
    
      downloadPdf() {
        if (this.plt.is('cordova')) {
          this.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, 'myletter.pdf', blob, { replace: true }).then(fileEntry => {
              // Open the PDf with the correct OS tools
              this.fileOpener.open(this.file.dataDirectory + 'myletter.pdf', 'application/pdf');
            })
          });
        } else {
          // On a browser simply use download!
          this.pdfObj.download();
        }
      }
    
    }