首页 > 解决方案 > Unable to write a pdf base64 encoded file into android and ios device using ionic-native/file plugin

问题描述

I am using ionic native ("ionic-native": "2.4.1") and using the FileOpener plugin to open a pdf file which is getting as base64 encoded from the api response.I have tried several options to write the file using File.writeFile() method and it was writing as 0kb.When I use the following method the file was written with some filesize,but it is in invalid format.

import { FileOpener,File } from 'ionic-native';
declare var cordova: any
@Component({
    providers: [File,FileOpener]
})
openArrBuffer(b64Data)
    {
        const base64ToArrayBuffer = (b64Data) => {
            const binary_string =  window.atob(b64Data);
            const len = binary_string.length;
            const bytes = new Uint8Array(len);
            for (let i = 0; i < len; i++) {
              bytes[i] = binary_string.charCodeAt(i);
            }
            return bytes.buffer;
          }
          File.writeFile(cordova.file.externalDataDirectory,'testnew.pdf',b64Data,{replace: true}).then((response) => {
            //console.log('successfully wrote to file3',response);
            FileOpener.open( cordova.file.externalDataDirectory+ 'testnew.pdf','application/pdf').then((response) => {
              //console.log('opened PDF file successfully3',response);
            }).catch((err) => {
                //console.log('error in opening pdf file3',err);
            });
          }).catch((err) => {
    
            //console.log('error writing to file3',err);
          });   
    }

In browser I can able to generate the pdf using the same base64 pdf

            const byteCharacters = atob(b64Data);
            const byteNumbers = new Array(byteCharacters.length);
            for (let i = 0; i < byteCharacters.length; i++) {
                byteNumbers[i] = byteCharacters.charCodeAt(i);
            }
            const byteArray = new Uint8Array(byteNumbers);
            //console.log(byteArray);
            var blobFile = new Blob([byteArray], { type: 'application/pdf' });            
            var fileURL = URL.createObjectURL(blobFile);
            window.open(fileURL, '_blank', 'location=no'); 

Can anyone suggest a solution to open a base64 pdf in ionic 2

标签: angularjsionic-frameworkionic2

解决方案


推荐阅读