Creating and Opening PDF on Ionic 1 on iOS

Recently I ran into an issue using the PdfMake on Ionic 1 on iOS. It works fine on the browser with a simple download or open command but not on the actual device.

Install the cordova libraries:

cordova.plugins.fileOpener2
cordova-plugin-file

Download the pdfmake javascript files and include them in your index.html

<script src='build/pdfmake.min.js'></script>
<script src='build/vfs_fonts.js'></script>

The code:

  var self = this ; // defined on top of the file

  var docDefinition = { content: 'This is an sample PDF printed with pdfMake' };

            self.pdfObj = pdfMake.createPdf(docDefinition);

            if (window.cordova) {
                self.pdfObj.getBuffer(function (buffer) {
                    var blob = new Blob([buffer], { type: 'application/pdf' });
                    // Save the PDF to the data Directory of our App
                    $cordovaFile.writeFile(cordova.file.dataDirectory, 'myletter.pdf', blob, { replace: true }).then(function () {
                        // Open the PDf with the correct OS tools
                        cordova.plugins.fileOpener2.open(cordova.file.dataDirectory + 'myletter.pdf', 'application/pdf');
                    })
                });
            }

Setup Config.xml

In your config.xml make sure you have the file settings

<preference name="AndroidPersistentFileLocation" value="Compatibility" />
<preference name="iosPersistentFileLocation" value="Library" />

How To Embed and Open PDF files in Ionic App on iOS

This is a solution for storing and opening pdf files inside your app for offline use.

  cordova.plugins.fileOpener2.open(
        cordova.file.applicationDirectory + 'www/img/sample.pdf',
        'application/pdf',
        {
          error: function (e) {
            console.log('Error status:'+e.status+'- Error message:'+ e.message);
          },
          success: function () {
            console.log('file opened successfully');
          }
        }
      );

Opening the pdf should be fairly simple using the cordova.plugins.fileOpener2 plugin, but I ran into a strange issue because my app name in the config.xml contained a space such as: <name>My App</name>. This caused the iOS to misread the file path. Removing this space in the app name fixed the file path on iOS.

I put the sample pdf doc in the ionic project under my images folder www/img/sample.pdf.

Good luck!

How To Print Textarea With Javascript in Ionic

How To Print Textarea With Javascript?

$scope.printText = function(){

    // replace the printTextArea with your id
    childWindow = window.open('','childWindow','location=yes, menubar=yes, toolbar=yes');
    childWindow.document.open();
    childWindow.document.write('<html><head></head><body>');
    childWindow.document.write(document.getElementById('printTextArea').value.replace(/\n/gi,'<br>'));
    childWindow.document.write('</body></html>');
    childWindow.print();
    childWindow.document.close();
    childWindow.close();
}

How To Use Ionic & Angular q Promises?

The Deferred API

A new instance of deferred is constructed by calling $q.defer().

The purpose of the deferred object is to expose the associated Promise instance as well as APIs that can be used for signaling the successful or unsuccessful completion, as well as the status of the task.

Methods

resolve(value) – resolves the derived promise with the value. If the value is a rejection constructed via $q.reject, the promise will be rejected instead.

reject(reason) – rejects the derived promise with the reason. This is equivalent to resolving it with a rejection constructed via $q.reject.

notify(value) – provides updates on the status of the promise’s execution. This may be called multiple times before the promise is either resolved or rejected.
Properties

promise – {Promise} – promise object associated with this deferred.

// for the purpose of this example let's assume that variables `$q` and `okToGreet`
// are available in the current lexical scope (they could have been injected or passed in).

function asyncGreet(name) {
  var deferred = $q.defer();

  setTimeout(function() {
    deferred.notify('About to greet ' + name + '.');

    if (okToGreet(name)) {
      deferred.resolve('Hello, ' + name + '!');
    } else {
      deferred.reject('Greeting ' + name + ' is not allowed.');
    }
  }, 1000);

  return deferred.promise;
}

var promise = asyncGreet('Robin Hood');
promise.then(function(greeting) {
  alert('Success: ' + greeting);
}, function(reason) {
  alert('Failed: ' + reason);
}, function(update) {
  alert('Got notification: ' + update);
});

This code example was taken from Angular Documentation page: https://docs.angularjs.org/api/ng/service/$q

How to use ng-disabled with multiple expression

You may have ran into this issue when trying to bind a submit button with multiple disable conditions. The easiest way to do this is to embed the variable checking in the html as follows:

Both variable must be false for the button to be disabled:

<button class="button" ng-disabled="(!data.var1 && !data.var2) ? false : true">
</button>

Either variable can be false for the button to be disabled:

<button class="button" ng-disabled="(!data.var1 || !data.var2) ? false : true">
</button>

How To Open Chrome Device Debugger?

Last night I was trying to open the chrome debugger for an ionic app running on my ios device but could not remember the URL. This was a very simple thing but was nearly impossible to discover on the internet for some reason…

To do this: Open Chrome Browser and type chrome://inspect/ in the url field.

I don’t know why Chrome and Google make this so hard to discover.