Print Data To Paper Or PDF Using Ionic Framework

Have you ever built an app that has heavy content that might need to one day be printed to a PDF or to paper?  Maybe you’re building the next great email or news app, both of which have an expectation that you should be able to print what you’re reading.

Both iOS and Android have printing functionality.  We are using Ionic Framework, and lucky for us, printing to either of these platforms couldn’t be easier when we use the Apache Cordova Printer Plugin by Sebastian Katzer.

Before starting this tutorial it is important to note that printing is only available on Android devices that have OS 4.4.4 (KitKat) or higher.  To print to a printer on both Android and iOS, it must first be configured in your devices settings.

Let’s start by creating a new Ionic Android and iOS project:

It is important to note that if you’re not using a Mac, you cannot add and build for the iOS platform.

At this point we are ready to install the base Apache Cordova plugin.  This can be done by running the following from your command prompt or terminal:

Technically, we can now start using the plugin in our app.  Like with most plugins, they cannot be tested from a web browser because they use native device code.

Before we go any further, we are going to include the AngularJS extension set, ngCordova into our application.  We are doing this because it makes life incredibly easy when handling plugins in Ionic Framework applications.

Because ngCordova is still alpha, I encourage you to not download the latest version when following this tutorial.  Although it could work, there are still chances breaking changes were introduced after I wrote this article. Instead, download commit 9b05b6 from the GitHub repository since it is the version I’m using.

Extract ng-cordova.min.js into your project’s www/js directory.  With the library file include in your project structure, open your www/index.html file and include the following above the cordova.js line:

It is very important to include ngCordova above the cordova.js line, otherwise you’re going to get strange results.  The final thing we need to do in order to have ngCordova working correctly in our project is to make a small change to the www/js/app.js file’s angular.module function:

We are now ready to get down to business.  Create the following ExampleController in your www/js/app.js file:

The $scope.print function will first check to see if printing is available on the device.  It will only be available on iOS devices with AirPrint and Android 4.4.4+ devices.  If available, $cordovaPrinter.print will attempt to print my personal profile remote website http://www.nraboy.com.

To use this controller and function, open your www/index.html file and add the following:

Don’t be fooled.  This plugin can print beyond just remote web pages.  Instead of passing in a URL, you can also pass in a string of HTML code.  There are actually a bunch of other options you can pass:


Option Name Type Description
name string The name of the print job
printerid string The identifier of the printer to be used for the print job
duplex boolean Specifies the duplex mode to use
landscape boolean The orientation for the printed content
grayscale boolean Whether or not to print with only black ink
bounds array The size and position of the print view

If you plan to pass options, you would just overload the function like $cordovaPrinter.print(src, options).  More documentation can be found on the plugins GitHub page.

A video version of this article can be seen below.

Nic Raboy

Nic Raboy is an advocate of modern web and mobile development technologies. He has experience in Java, JavaScript, Golang and a variety of frameworks such as Angular, NativeScript, and Apache Cordova. Nic writes about his development experiences related to making web and mobile development easier to understand.

  • great work nic, thank you.
    is it possible with ionic to view a pdf file that is stored in a webserver (cors are nor enabled) where the app is not running in android? it works on ios with cordova webview plugin, but not on android.
    thanks isaid

    • Will the InAppBrowser plugin accomplish this for you?

      I believe by default, Android does not ship with any PDF readers. You’d have to make one or download one.

      Regards,

      • Yes the InAppBrowser plugin from cordova
        In ios it shows the pdf but in android i use google docs to view it online.
        It would be easier if android has by default a pdf reader like ios do

  • opyate

    It’d be nice if the data in its raw format can be attached to the PDF, which is the problem I’m trying to solve with https://pdfcrun.ch

    • I think that is beyond the scope of what the OS level functionality can handle. You’d have to design your own PDF tools if you wanted that.

      I don’t know what you linked because I don’t open links I don’t recognize. Sorry.

      Regards,

      • opyate

        PDF attachments is a thing, and any good PDF tool should support it. The link I posted is something I built to turn PDFs into data. Click, it won’t bite 😛

        • Sorry, I didn’t mean to suggest your link was malicious. I just don’t follow links in my comments that go beyond GitHub, Bitbucket, CodePen, and Pastebin. Personal preference.

          If the link looked malicious, I would have deleted the comment.

  • Yas

    Hi Nic,

    I tried this on a virtual terminal with Android 4.4.4. Unfortunately, in the ADB logs I get this error:

    TypeError: Cannot read property ‘printer’ of undefined

    at Object.isAvailable (file:///android_asset/www/js/ng-cordova.min.js:9:17736)

    at Scope.$scope.print (file:///android_asset/www/js/controllers.js:217:28)

    What can I do to solve this problem?

    • Well, what do you have at line 217 in controllers.js?

      My assumption is that you’ve got a typo somewhere. If you put your project on GitHub, I can take a look.

      Regards,

      • Yas

        I finally found out that the plugin was not added properly.

        I tried several times to add it again by running the command

        cordova plugin add https://github.com/katzer/cordova-plugin-printer.git

        This didn’t work, and I still don’t know why.

        If someone is facing the same problem, I recommend you to download the plugin then use the following command:

        cordova plugin add de.appplant.cordova.plugin.printer –searchpath path/to/local/folder/of/the/plugin

        Nic, I can’t find words to thank you the way you deserve for everything.

        • I’m glad you got it working 🙂

  • Annie

    Hi Nic,

    I tried using this method to print to PDF in iOS. It didn’t work. It just shows the Print option.

    Is it that the printer plugin can only print in iOS and not generate a PDF?

    • The plugin uses the native features of the operating system. When I tried in my iOS simulator it worked without issue. What version of iOS are you using?

      Regards,

      • Annie

        iOS 8.1.2

        I did see a few issues that were listed in the plugin’s github with iOS 8. But they were all related to seeing whitepages, etc. It wasn’t that the option to save as pdf itself did not appear.

        Could the version be the problem?

        • You’re right! I don’t know what I was thinking. I went back to try and the option was not there for iOS. I then did a Google search and Apple hasn’t added this functionality yet.

          Unfortunately, iOS will be restricted to a physical printer for now.

          Regards,

          • Annie

            Hi Nic,

            Thanks for confirming!
            I decided to use a server side solution for generating the pdf.

            Regards,
            Annie

  • kyburn

    is there a way to rename the created PDF file?

    • I believe you do that via any prompt that shows when you call the function. I think it is an OS level thing.

  • Nathalia Nascimento

    Is it possible to set the filepath?

  • Bart

    Hey Nic, Thanks for all your great tutorials! 🙂
    Would it be possible to directly print something, without popups that ask if you want to use a printer or save it as a pdf. I would like to make an app for a big company, where people can choose at wish desk they want to be and a small printer prints their ticket. I’m searching for a solution to print without any popup or so that asks “if you’re sure”, or “which printer you want to use”.

    Thanks a lot for you advice!
    Regards, Bart

    • Printing is baked into the OS. I don’t believe you’re going to be able to force print unless your printer has APIs. Only the manufacturer would know this and since there are tons of manufacturers, this approach would never work out.

  • rejinthala manoj

    Hi Nic,
    i want to create a PDF and put the data consisting of text and images i want put the data as it is displayed on the webpage here i attached screen shot of that. please provide any link or solutions for that.thanks in advance.please ignore edit and delete symbols.

    regards
    manoj

    • Maybe try this library?:

      https://github.com/MrRio/jsPDF

      • rejinthala manoj

        that working good but i need to share that PDF instead of downloading.

        • Maybe something like this?:

          https://www.thepolyglotdeveloper.com/2015/01/upload-files-remote-server-using-ionic-framework/

          You really are not giving me much information to go off of. It would be a good idea for you to give me thorough answers of what you’re trying to do.

          Regards,

          • rejinthala manoj

            i am getting a text from service and i displayed that content on page.so user can edit the content getting from the service.after editing the code he can share that content via facebook and email.when user share the content via email the complete page content should share as a pdf

          • rejinthala manoj

            please replay on this

          • Social sharing expects images, not PDFs. Email can send PDFs if you first print to PDF and then send an email using the email plugin with an attachment file.

            Neither have anything to do with this tutorial.

            Regards,

  • Gobinath Sekar

    Hi Nic,
    I want to print the text on connected printer,but it was not detect the printer,only saves the PDF

    • You may not have a compatible WiFi printer then. You’ll have to check how to properly configure your printer if it is compatible. The plugin only uses the core OS APIs. This means your OS cannot find the printer, not the plugin.

      Best,

  • multilexus

    Hello Nic, another great tutorial from you, as always! 🙂 I know this is a bit off topic, but is there ANY way to print a PDF doc “silently”, without generating a preview page? I’m using ionic/cordova on Android device. TIA!

    • You’d have do create your own plugin for this with your own unique device code. The plugin I wrote about uses the available OS APIs that are baked into the device. You’d have to create your own APIs.

  • jkapsi

    Hello! I was wondering if this plugin works with windows 10. I tried it with no luck so far. Is there anything for printing to pdf with windows 10?

    • I honestly don’t know. Most plugins not created by the Apache Foundation do not support Windows. This plugin like many are community driven.

  • bismark camargo

    ionic.bundle.js:26794 TypeError: Cannot read property ‘printer’ of undefined
    at Object.isAvailable (ng-cordova.min.js:9)
    at Scope.$scope.print (app.js:28)
    at fn (eval at compile (ionic.bundle.js:27638), :4:206)
    at ionic.bundle.js:65427
    at Scope.$eval (ionic.bundle.js:30395)
    at Scope.$apply (ionic.bundle.js:30495)
    at HTMLButtonElement. (ionic.bundle.js:65426)
    at defaultHandlerWrapper (ionic.bundle.js:16787)
    at HTMLButtonElement.eventHandler (ionic.bundle.js:16775)
    at triggerMouseEvent (ionic.bundle.js:2953)
    help!!!

      • bismark camargo

        ionic framework
        windows 10

        controller:
        app.controller(“ExampleController”, function($scope, $cordovaPrinter) {

        });
        //Error
        ionic.bundle.js:26794 TypeError: Cannot read property ‘printer’ of undefined
        at Object.isAvailable (ng-cordova.min.js:9)
        at Scope.$scope.imprimir (app.js:28)
        at fn (eval at compile (ionic.bundle.js:27638), :4:215)
        at ionic.bundle.js:65427
        at Scope.$eval (ionic.bundle.js:30395)
        at Scope.$apply (ionic.bundle.js:30495)
        at HTMLButtonElement. (ionic.bundle.js:65426)
        at defaultHandlerWrapper (ionic.bundle.js:16787)
        at HTMLButtonElement.eventHandler (ionic.bundle.js:16775)
        at triggerMouseEvent (ionic.bundle.js:2953)

  • pbpraveen

    Hello Nic,

    Nice article but i am confused on what basis it will check that printer is available or not on that mobile device ?.

    using Email ? or any other settings we have to do on that mobile app ?

    Please Let me know , its urgent.

    Thank You

    • The plugin interfaces with the platform OS. How the underlying printer works is dependent on the device and operating system version. You might want to consult their documentation.

      Best,

  • Billy Goforth

    Hi Nic, great tutorial. I can download pdf on android with no issue, but I cannot download on iOS. It only offers print capability. Can you help me trouble shoot this or give me some tips as to what road to go down?

    Thanks

    B

    • It is up to the platform OS. All this plugin does is interface with the OS. If iOS doesn’t offer download as PDF, then we are out of luck when it comes to this plugin. You might want to visit the Apple documentation or ping the plugin developer as to which is supported.

    • sonu sidhu

      Can i use printer without printing selection options for android?

  • sonu sidhu

    Hello NIC,

    Can i use printer without printing selection options for android?

  • edison

    am getting these error
    ionic.bundle.js:17917 Uncaught Error: [$injector:modulerr] Failed to instantiate module starter due to:
    Error: [$injector:modulerr] Failed to instantiate module ng-cordova due to:
    Error: [$injector:nomod] Module ‘ng-cordova’ is not available! You either misspelled the module name or forgot to load it. If registering a module ensure that you specify the dependencies as the second argument.

    • Are you injecting ngCordova or ng-cordova? The error you have says you didn’t include the library correctly.

      • edison

        ngCordova

        • Put your full project on GitHub and I’ll have a look.

  • Hi Nic,

    Is this plugin support printing to bluetooth printer?

    Thanks

  • Janwari Farqi

    hy nic, i have problem like this :
    TypeError: Cannot read property ‘printer’ of undefined
    at Object.isAvailable (ng-cordova.js:6197)

    i have add plugin in my ionic.
    what’s the problem? can you help me?

  • Alica Casaligi

    I am using angular-pdf to display PDF in ionic app.
    https://github.com/sayanee/angularjs-pdf
    With your code my app redirects to google cloud print. But it doesn’t show PDF there.

    • This plugin uses the native iOS and Android print features. So yes on Android printing would use Google Cloud Print which should let you print to paper or PDF. I doubt it would work in combination with the library you listed.

  • Daxesh Vekariya

    hi nic

    please Solve My Problem.

    i don’t want to particular sight page print but i wan’t cordova plugin printer pass it the list of records that are currently displayed in Application. Please Help Me.

    • You’ll need to write your own logic to generate an HTML page from your data and print that. The plugin was not designed to print anything you throw at it.

      Best,

  • Game Eiei

    doesn’t work 🙁

  • Daxesh Vekariya

    hi nic please solve my problem for display my data is can’t proper as like https://uploads.disquscdn.com/images/4bc269279e716e44173ce6683cccb8e01e46a0fb098cdd1d81d5834f0d02de25.png

    ionic card display format of data is can’t same as display in database.i wan’t to display my data as same format as a database like
    https://uploads.disquscdn.com/images/4cf3e7f64cc6677fbc3a00ca65c38fad7743258366d9164d25efa35d66766068.png

    Here is my code

    {{item.address}}

  • Nathália Cechetti

    Error: [$injector:unpr] Unknown provider: $cordovaPrinterProvider <- $cordovaPrinter