How to Print in Ionic 4 | Printing with Ionic 4

All examples given in this tutorial is tested and will be working fine with the Ionic 4 framework.

In this tutorial, you will learn how to print in Ionic using Ionic printer native plugin.

Printing document in Ionic

Ionic is the perfect choice to create a hybrid application. It provides a quick way to build an app in no time. But, sometimes it is very difficult and awful to access mobile hardware like a camera, file storage, Bluetooth, etc.

To create the functionality of printing documents or HTML rendered contents in ionic is easy if you know the plugins which are built for this.

It can be implemented using an Ionic native and Cordova printer plugin.

So let’s start from scratch by creating a new ionic app.

Create a new Ionic Application

We will create a brand new application using the Ionic CLI. Here, we are using the latest version of Ionic CLI 5.4.12.

You can also check the CLI version of Ionic in your system by running the following command in command prompt or terminal.

Ionic -v or ionic --version 
5.4.12 // output (You can get a different version).

Make sure to update the latest version of CLI globally on your system by issuing the following command given below:

npm install -g ionic@latest
Or
npm i -g ionic@latest

Try using “sudo” if you find any npm error in ubuntu or macOS.

Now you have updated Ionic CLI to the latest version. So, create an app with a blank template by running the command:

ionic start IonicPrinter blank --type=angular
cd IonicPrinter
ionic platform add android

If you are using  macOS, you can also target IOS by running the following command:

ionic platform add iOS

Install Cordova and Ionic Native Printer Plugin

Run the following command to install the native printer plugin to access its features.

ionic cordova plugin add cordova-plugin-printer
npm install --save @ionic-native/printer@4

Import Ionic Printer Plugin in App Module

To use the printer plugin in the ionic app we need to import it in the app module file. So go to the project folder and navigate to the app.module.ts file and open it.

Search the array called ‘providers’ and place the code as shown below.

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { RouteReuseStrategy } from '@angular/router';

import { IonicModule, IonicRouteStrategy } from '@ionic/angular';
import { SplashScreen } from '@ionic-native/splash-screen/ngx';
import { StatusBar } from '@ionic-native/status-bar/ngx';

import { AppComponent } from './app.component';
import { AppRoutingModule } from './app-routing.module';

// import printer plugin
import { Printer } from '@ionic-native/printer';

@NgModule({
  declarations: [AppComponent],
  entryComponents: [],
  imports: [BrowserModule, IonicModule.forRoot(), AppRoutingModule],
  providers: [
    StatusBar,
    SplashScreen,

    // added to providers array
    Printer,

    { provide: RouteReuseStrategy, useClass: IonicRouteStrategy }
  ],
  bootstrap: [AppComponent]
})
export class AppModule {}

Now, We have imported the printer plugin to use in our app.

Use Printer in Our App Home Component

To use printer plugin, open the home.page.ts file and add the following code to test the printing integration.

import { Component, OnInit } from '@angular/core';
import { Printer, PrintOptions } from '@ionic-native/printer/ngx';

@Component({
  selector: 'app-home',
  templateUrl: 'home.page.html',
  styleUrls: ['home.page.scss'],
})
export class HomePage implements OnInit {

  constructor(
    private printer: Printer
  ) {}

    ngOnInit(){}

    printDocument() {
        this.printer.isAvailable().then((onSuccess) => {
            let options: PrintOptions = {
                font: {
                    size: 22,
                    italic: true,
                    align: 'center'
                },
                header: {
                    height: '6cm',
                    label: {
                        text: "\n\nHeader text",
                        font: {
                            bold: true,
                            size: 37,
                            align: 'center'
                        }
                    }
                },
                footer: {
                    height: '4cm',
                    label: {
                        text: 'Footer text',
                        font: { align: 'center' }
                    }
                }
            };
    
            let content = "Hello World";
            this.printer.print(content, options);

        }, (err) => {
            console.log('Error', err);
        })  
    }
}

Now, you need to hook the print() function with your home.page.html file. So that, when a user clicks on the print button the print() function gets called.

<ion-header>
  <ion-toolbar>
    <ion-title>
      Ionic Blank
    </ion-title>
  </ion-toolbar>
</ion-header>

<ion-content>
  <div class="ion-padding">
    The world is your oyster.
    <p>If you get lost, the <a target="_blank" rel="noopener" href="https://ionicframework.com/docs/">docs</a> will be your guide.</p>
  </div>
  <button type="button" mat-button color="primary" (click)="printDocument()"></button>
</ion-content>

Now, make sure to connect with a mobile device using the USB cable and run the following command:

ionic run android // for android device only

Conclusion

Finally, print in ionic explanation is done, you can also visit the Cordova GitHub repository or ionic native printer plugin example to see in detail.

Leave a Reply