Opening A PDF in Ionic on Android

Posted on Updated on

Well, after nearly a week of trial and error of trying out other people’s tutorials and having no luck, and getting very frustrated…  I’d like to present my findings of what has worked for me.

Please understand, this example will NOT work straight out of the box. You’ll need to modify your code. I post these things, so I don’t forget how I did it, but hopefully so you can learn and use them too. The post is subject to change and be updated.

Oh, and this image too. It’s me…

DbzLJyiU8AIosGS

I finally found the last piece to my solution here.

Firstly, this will probably (I’m guessing) on of the most important things in the future to know, as the Ionic framework, Cordova, PhoneGap, NodeJS is changing so rapidly, it could not work tomorrow. So, here are the important values of version numbers for you.

$ ionic info

cli packages: (/usr/local/lib/node_modules)

@ionic/cli-utils : 1.19.2
 ionic (Ionic CLI) : 3.20.0

global packages:

cordova (Cordova CLI) : 7.1.0

local packages:

@ionic/app-scripts : 3.1.9
 Cordova Platforms : android 6.4.0 ios 4.5.4
 Ionic Framework : ionic-angular 3.9.2

System:

Node : v8.11.1
 npm : 5.6.0 
 OS : macOS High Sierra

Environment Variables:

ANDROID_HOME : not set

Misc:

backend : pro

newspaper.ts

import { Component, NgZone } from '@angular/core';
import { IonicPage, NavController, NavParams, Platform } from 'ionic-angular';
import {Http} from '@angular/http';
import { GlobalsService } from '../../globals/globals'; 
import 'rxjs/add/operator/map';
import { File } from '@ionic-native/file';
import { FileTransfer, FileTransferObject } from '@ionic-native/file-transfer';
import { DocumentViewer } from '@ionic-native/document-viewer';
import { FileOpener } from '@ionic-native/file-opener';

@Component({
 selector: 'page-newspaper',
 templateUrl: 'newspaper.html',
})
export class NewspaperPage {

constructor(public navCtrl: NavController, public navParams: NavParams,
 private http: Http,
 public globalsvals: GlobalsService,
 private file: File,
 private transfer: FileTransfer,
 private platform: Platform,
 private document: DocumentViewer,
 private fileOpener: FileOpener
 ) {
 }
 
 posts: any;

 url: string = '/newspaper/json.php';
 myAssociativeArr: any = []; 
 items1: any = [];
 
ionViewDidLoad()
 {
 console.log('ionViewDidLoad NewspaperPage');
 console.log(this.globalsvals.newspaperpdf_json); 
 
 if (this.globalsvals.release == true)
 {
 this.url = this.globalsvals.newspaperpdf_json;
 } 
 
 this.http.get( this.url )
 .map(res => res.json())
 .subscribe(data => { 
 this.items1 = data; 
 //console.log (this.items); 

 // With this, I can now get each record as it loops through them
 
 for (const item of this.items1.items)
 {
 console.log (item.url); 
 var newElement={}; 
 newElement["url"] = item.url;
 newElement["filename"] = item.filename;
 this.myAssociativeArr.push(newElement);
 }
 }); 
 }
 
itemTapped(event, item) 
{
 console.log("Item Tapped"); 
 let path = null;
 
 if (this.platform.is('ios')) {
 path = this.file.documentsDirectory;
 } else if (this.platform.is('android')) {
 path = this.file.dataDirectory;
 } 
 
 const transfer: FileTransferObject = this.transfer.create();
 console.log(item.url);
 const url = item.url;
 transfer.download(url, this.file.dataDirectory + 'file.pdf').then((entry) => {
 console.log('download complete: ' + entry.toURL());

 this.fileOpener.open( this.file.dataDirectory + 'file.pdf', 'application/pdf')
 .then(() => console.log('File is opened'))
 .catch(e => console.log('Error opening file', e)); 
 
 }, (error) => {
 // handle error
 }); 
 
 }
}

newspaper.html

<ion-header>
  <ion-navbar> 
    <ion-title><img alt="logo" height="40"  src="./assets/images/logo.png" ></ion-title>
  </ion-navbar>
</ion-header>


<ion-content padding>  
  <h2>Newspapers</h2>
      
<ion-list>          
   <ion-item ion-item *ngFor="let item of myAssociativeArr" >
    <ion-item ion-item *ngFor="let item of myAssociativeArr" >
     <ion-row>
      <ion-col col-2>
       <button icon-only (click)="itemTapped($event, item);" style="background-color: white !important;"> 
         <img [src]="item.thumb">
        </button>
       </ion-col>
       <ion-col col-10>
         <h1 (click)="itemTapped($event, item);" [innerHTML]="item.title_date">
         </h1>
       </ion-col>
      </ion-row> 
    </ion-item>
  </ion-list>
</ion-content>

My JSON feed file for PDFs can be found here: (which you’ll need to configure)
https://github.com/vrdriver/JSONpdffeed

You'll probably also need to add the cordova plugins for the following:

import { File } from '@ionic-native/file'; 
import { FileTransfer, FileTransferObject } from '@ionic-native/file-transfer'; 
import { DocumentViewer } from '@ionic-native/document-viewer'; 
import { FileOpener } from '@ionic-native/file-opener';

Add them to your app.module.ts file like that, and also as a provider, in that same file.

 File,
 FileTransfer,
 DocumentViewer,
 FileOpener

You may notice I have a globals.ts file as well. It’s just my way of keeping track of global variables.

import { Injectable } from '@angular/core';

@Injectable()
export class GlobalsService
{
    // If this is for a release, set this to true, so that all of the values will
    // not use proxie values.  
    // SET THIS TO TRUE IF YOU ARE DEPLOYING
    public release:boolean = true;  
    public newspaperpdf_json:string = 'https://resources.site.com/apps/pdf/newspaper/json.php';    
}

The other thing with my code, is you’ll also notice that I’m using a few proxies as well. This is the reason for the “release” variable. If it’s a deployed (finalised) app, then I’ll set this value to true, and it’ll change all the code to pull in the correct URLs – as well as a few other minor non-dev things.

Some sites claimed to have these lines work. They did not.

this.document.viewDocument(url, 'application/pdf', {});
window.open(encodeURI(path + 'c4i.pdf'), '_system');

Still, other well respected sites, claimed files would work, that when their example loaded, it pointed the user to download a file from the Android Play Store to open the PDF file… ???

These to me, were not options. Some claimed to work with open the file is a webkit browser window… Why would you do it that way anyway? I have a native PDF viewer, let’s use it.

I hope this document is as clear as mud. I’ll be doing more tests, and probably updating it as I discover more things. But, as it stands, it worked… so far. 🙂

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s