Hi, I tried during weeks, and I finally got a solution to download a pdf from a service and show it in iOS and Android, works perfect in both platforms:
Install Plugins
We need to install InAppBrowser, File and FileOpener plugins. Remember to include all this plugins in your app.modules.ts
.
The component
This is the structure of my pdf-viewer.ts
component:
import { Platform } from 'ionic-angular';
import { File } from '@ionic-native/file';
import { InAppBrowser } from '@ionic-native/in-app-browser';
import { FileOpener } from '@ionic-native/file-opener';
//include api-service.ts to get the pdf
import { ApiService } from '../../providers/api-service';
@Component({
selector: 'pdf-viewer',
templateUrl: 'pdf-viewer.html'
})
@Pipe({ name: 'safe' })
export class myComponent {
constructor(
...
private file: File,
private fileOpener: FileOpener,
private plt: Platform,
...
) {
...
}
...
blobPdf; // Here we will store our Blob
openPdf(){
this.apiService.getPdf().subscribe(
data => {
if (this.plt.is('ios')) {
// Use inAppBrowser plugin,
// easier and faster in iOS
this.pdfobj.active = false;
this.pdfobj.fileURL = URL.createObjectURL(data);
var browser = this.iab.create(
this.pdfobj.fileURL,
'_blank',
'location=no,' +
'toolbar=yes,' +
'enableViewportScale=yes,' +
'closebuttoncaption=Cerrar PDF,' +
'hardwareback=no'
);
browser.show();
} else if (this.plt.is('android')) {
// lets save and then open the file
this.blobPdf = data; // Lets store the pdf Blob
let filedir = this.file.dataDirectory;
this.file.writeFile( //save PDF
filedir,
"comprobante.pdf",
this.blobPdf,
{replace:true}
).then(() =>{
this.fileOpener.open( //open in native PDF
filedir + 'comprobante.pdf',
'application/pdf'
).then(() => {
this.pdfobj.active = false;
}).catch(e => console.log('Open error', e));
}).catch(e => console.log('Save error',e));
}
},
(error) => {
this.appService.manageError(error);
}
);
}
The service
This the code for appi-service.ts
file:
import { Injectable } from '@angular/core';
import { Http, Headers, Response, RequestOptions, ResponseContentType } from '@angular/http';
import { Observable } from 'rxjs/Rx';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';
@Injectable()
export class ApiService {
constructor (
public http: Http
){}
handleError(error, errorType) {
return Observable.throw(error);
}
getPdf (): Observable<Array<any>> {
var url = YOURSERVICEURL + '/getabeautypdfinbase64/';
var headersXML = new Headers({
'Content-Type': 'application/json',
});
let options = new RequestOptions({
headers: headersXML,
responseType: ResponseContentType.Blob //here is the magic!!!
});
return this.http.get(url, options)
.map(
(res) => {
//CHANGE THE BASE64 DATA INTO A PDF BLOB
return new Blob([res.blob()], { type: 'application/pdf' })
})
.catch(this.handleError);
}
}
And ready, this way you can open a Base64 pdf from a service in iOS and Android