Ionic - Base64 PDF


#1

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.


#2

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.


#3

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’)
          });```

How to transform base64 to pdf IONIC 2
Save PDF file from base64 string in ionic in local folder
#4

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?


#5

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:

() => {}

#6

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

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

}


#7

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

Anes


#8

Check Below One


#9

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


#10

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


#11

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

i dont know where my code got wrong


#12

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.