Ionic - Base64 PDF

I am currently developing a mobile project using Cordova and Ionic2 using an external database resource that connects to the mobile via REST webServices.

The database has documents pdf saved that you have to send to the mobile and view the same. I am using the pdf in enconding Base64 through the webservices by Json.

I can get the string in base64, but I do not quite understand how to decode it and save it on mobile, which is Android to be able to see it.

Personally I couldn’t get base64 encoding and decoding of a PDF to work at all, because when decoding on the device part of the pdf file was just… gone (certain characters.) I ended up setting up a download link and using Transfer to download the file, and FileOpener to open it.

If you literally mean how to decode a base64 in javascript, it’s atob(), and btoa() to encode. If you want to try to get decoding and saving the file working, though I spent quite some time never succeeding at that, use File to save the decoded string on the device.

install File and File Opener plugin.

File plugin
ionic cordova plugin add cordova-plugin-file
npm install --save @ionic-native/file

File Opener plugin:
cordova plugin add cordova-plugin-file-opener2
npm install --save @ionic-native/file-opener

//base 64
let downloadPDF: any = ‘W0JFR0lOXQolUERGLTEuMgp6R1/V+d9KpBi3sCNzNh…….’
        fetch('data:application/pdf;base64,' + downloadPDF,
          {
            method: "GET"
          }).then(res => res.blob()).then(blob => {
            this.file.writeFile(this.file.externalApplicationStorageDirectory, 'statement.pdf', blob, { replace: true }).then(res => {
              this.fileOpener.open(
                res.toInternalURL(),
                'application/pdf'
              ).then((res) => {

              }).catch(err => {
                console.log(‘open error’)
              });
            }).catch(err => {
                  console.log(‘save error’)     
       });
          }).catch(err => {
                 console.log(‘error’)
          });```
2 Likes

Hi, I am a beginner with ionic.

I get an error when I run your code: “TypeError: Cannot read property ‘file’ of undefined”

I think “this.file.writeFile” is not found!?

Here is my code:

constructor(public afs: AngularFirestore, private authProvider: AuthProvider, public file: File) {

this.usersCollection = this.afs.collection('users', ref => ref.orderBy('title', 'asc'));

this.users = this.usersCollection.snapshotChanges().map(changes => {
  return changes.map(a => {
    const data = a.payload.doc.data() as User;
    data.id = a.payload.doc.id;
    return data;
  });
});

}


getMaklermandat() {

let docRef = this.afs.doc('users/' + this.authProvider.getcurrentUser());
docRef.ref.get().then(function (doc) {
  if (doc.exists) {
    let user: User = doc.data();
    let downloadPDF: any = user.maklermandat;

    fetch('data:application/pdf;base64,' + downloadPDF, {
      method: "GET"
     }).then(res => res.blob()).then(blob => {
    //  this.file.writeFile(this.file.dataDirectory, 'file.pdf', blob)
     this.file.writeFile(this.file.externalRootDirectory, 'statement.pdf', blob, {
         replace: true
       }).then(res => {

     this.fileOpener.open(
          res.toInternalURL(),
          'application/pdf'
        ).then((res) => {

        }).catch(err => {
          console.log('open error')
        });
      }).catch(err => {
        console.log('save error')
      });
    }).catch(err => {
      console.log('error:' + err)
    });

    console.log(downloadPDF);
    //window.open(pdf);
  } 
  else {
    console.log("No such document!");
  }
}).catch(function (error) {
  console.log("Error getting document:", error);
});

}

What do I wrong?

You need to use arrow functions instead.

function() {}

Should be

() => {}

Some more notes:

If you’re expecting 1 parameter, use this format:

param => {}

If you’re expecting more parameters, or 1 parameter of a certain type, use this format:

(param1: Object, param2: number) => {}

If you’re not expecting any parameters, use:

() => {}

import { FileOpener } from ‘@ionic-native/file-opener’
import { File } from ‘@ionic-native/file’;

in Constructor
constructor(private file: File, private fileOpener: FileOpener){

}

Hi Sathasivam,
I used your code . But there is no actual download occur. Got that 64 bit encoded string in response . Please advise

Anes

Check Below One

Dear Sathasivam,
I already included those dependencies. Please look my thread and code here : Could not download PDF from base 64 data from web service . Why?

Please advise

Anes

Dear @Sathasivamr,

this code works fine in Android 6.0.1 (2016 - Marshmellow) Samsung mobiles, 5.1 (Lolipop) Micromax mobile but not in 5.1.1 Lolipop Samsung device & 7.0 Nougat Lenovo device. This is my problem. In not working
mobiles that PDF not created …

any body have a solution ?

Thanks
Anes

hey, im new to ionic and everytime i ran my code i get this.

base64togallery

i dont know where my code got wrong

Here, The Android file directory opens using with this.file.externalDataDirectory it’s working fine, but the ios file open using what type of instance member I have to use.

doesn’t working Here is my code

downloadfile() {

let downloadPDF: any;
let Image :any;
  html2canvas(document.body).then(function (canvas) {
    document.body.appendChild(canvas);
    Image = canvas.toDataURL("img/png");
   // downloadPDF = /,(.+)/.exec(reader.result)[1];
   downloadPDF = Image.substr(22);
   console.log(downloadPDF);

    fetch('data:application/pdf;base64,' + downloadPDF,
      {
        method: "GET"
      }).then(res => res.blob()).then(blob => {
        this.file.writeFile(this.file.externalApplicationStorageDirectory, 'statement.pdf', blob, { replace: true }).then(res => {
          this.fileOpener.open(
            res.toInternalURL(),
            'application/pdf'
          ).then((res) => {
            console.log('response',res);
            

          }).catch(err => {
            console.log('open error')
          });
        }).catch(err => {
          console.log('save error')
        });
      }).catch(err => {
        console.log('error')
      });

  });

}

Hi Sathasivam,

I’m using the same code and getting the below error.
Kindly help me to resolve this.

*Refused to connect to ‘data:application/pdf;base64,SGVsbG8gV29ybGQ=’ because it violates the following Content Security Policy directive: "default-src ". Note that ‘connect-src’ was not explicitly set, so ‘default-src’ is used as a fallback.

Refused to connect to ‘data:application/pdf;base64,SGVsbG8gV29ybGQ=’ because it violates the document’s Content Security Policy.

Thanks in advance.

did you find a solution to the problem?