I have base 64 String that I need to convert and show it as pdf/ image or doc/excel etc… depending on the content type of the base 64 String…


#1

I have base 64 String that I need to convert and show it as pdf/ image or doc/excel etc… depending on the content type of the base 64 String…
So I did it this way to show open a pdf file with zoom in feature.

import {FileOpener} from “@ionic-native/file-opener”;
import {File} from “@ionic-native/file”;

constructor(public navParams: NavParams,
private file: File,
private fileOpener: FileOpener) {
}

parseResponse(data) {
console.log(data);
if(data.contentType == ‘application/pdf’){
var newDocName = this.docName + “.pdf”;
this.writeDocToFile(newDocName, this.base64ToUint8Array(data.content).buffer, data.contentType);
} else if(data.contentType == ‘image/png’ || data.contentType == ‘image/jpeg’ || data.contentType == ‘image/gif’ ) {
var blob = new Blob([this.base64ToUint8Array(data.content)], { type: data.contentType });
var pngUrl = URL.createObjectURL(blob);
this.displayImage(pngUrl);
} else if (data.contentType == ‘application/msword’){
var newDocName = this.docName + “.doc”;
this.writeDocToFile(newDocName, this.base64ToUint8Array(data.content).buffer, data.contentType);
} else if (data.contentType == ‘application/vnd.ms-excel’){
var newDocName = this.docName + “.xls”;
this.writeDocToFile(newDocName, this.base64ToUint8Array(data.content).buffer, data.contentType);
} else if (data.contentType == ‘application/vnd.openxmlformats-officedocument.spreadsheetml.sheet’){
var newDocName = this.docName + “.xlsx”;
this.writeDocToFile(newDocName, this.base64ToUint8Array(data.content).buffer, data.contentType);
} else if (data.contentType == ‘application/vnd.openxmlformats-officedocument.wordprocessingml.document’) {
var newDocName = this.docName + “.docx”;
this.writeDocToFile(newDocName, this.base64ToUint8Array(data.content).buffer, data.contentType);
}
}

base64ToUint8Array(base64) {
var raw = atob(base64);
var uint8Array = new Uint8Array(raw.length);
for (var i = 0; i < raw.length; i++) {
uint8Array[i] = raw.charCodeAt(i);
}
return uint8Array;
}

writeDocToFile(fileName, data, contentType) {
this.file.writeFile(this.file.dataDirectory, fileName, data, {replace: true})
.then(result => {
console.log(result);
alert(result.nativeURL);
this.fileOpener.open(result.nativeURL, contentType)
.then(result => {
console.log(“File Opepend”);
console.log(result);

      })
      .catch(error => {
        console.log("File Open Error");
        console.log(error);
      })
    //this.basicAlert("blah", result.nativeURL);
  })
  .catch(error => {
    console.log(error);
  })

}


Zooming on pdf in ionic?
#2

Have you figured this out, some ppl were telling me to use PDF.js


#3

It worked for me. let me know if u find issues.