Open Documents in ionic 4 app : step by step Integration guide

Introduction

In one of my projects, I have added functionality for opening Documents (in-app) in ionic 4. So i am documenting the steps for achieving the functionality which would be a great help for myself, if i need any reference in future projects or for any other developers who might be not sure of how to go forward to achieve this functionality. Lets begin…

How it works?

So you have a remote url of a PDF file (or any document) which is being shown in your page content. When the user clicks on it, by normal behaviour it will try to open up in an external browser or an in-app browser (if you have one integrated in your app). What we want is that, when user clicks on the link, it will download the file in background and open the file swiftly in the device’s default pdf reader.

Adding plugins

I will be showing the integration steps on a blank ionic 4 project. If you are not familiar how create blank app project in ionic, follow the official ionic documentation  .  We will be adding the following plugins to get this functionality working:

  • File Transfer
    • commands to run
      • ionic cordova plugin add cordova-plugin-file-transfer
      • npm i @ionic-native/file-transfer
      • npm i @ionic-native/file
  • File Opener
    • commands to run :
      • ionic cordova plugin add cordova-plugin-file-opener2
      • npm install @ionic-native/file-opener

Adding code

creating a provider

We will now create a provider for pdf functionality with the following command:

ionic g service services/pdf-viewer

you will get the folder structure as follows:

services directory
services directory

In the pdf-viewer.service.ts file add the following code:

Now that we have defined our service , we can call it to the page we want to use . So now on our home page we can call the download method defined in service to download the pdf from url and open it with pdf viewer. Add the code in the homepage

HTML:

call the method from service into the home.page.ts file as follows:

Along with this, we will also have to reference the service and all the packages used in the service. Your app.module.ts file should look as follows:

Output

Once all the steps mentioned above are properly followed, when you build the app you should get the interface as follows:

 

 

 

 

 

 

Along with this, I have also attached a live demo of the working of PDF viewer. Check it out:

If this is not enough, you can check my github repository for the demo i have shown here!

Conclusion

I hope this article will help developers to achieve this functionality easily. If you have any doubts regarding this, Let me know in the comments section below! Moreover, If you want to read more articles regarding ionic 4 , Check it out here.

179
179