Kumar
Kumar

Reputation: 280

How to save Blob in Ionic

I am new to ionic framework, actually I am getting byte array as response from back end service and converting it to blob. How can I save it to PDF in ionic?

var blob = new Blob([res], { type: 'application/pdf' });

Here res is the response (byte array) from the service.

Code

var blob = new Blob([res], { type: 'application/pdf' });         

        let fileName="Receipt.pdf";         
        let filePath = (this.platform.is('android')) ? 
        this.file.externalRootDirectory : this.file.cacheDirectory;

        this.file.writeFile(filePath, fileName, blob, { replace: true }).then((fileEntry) => {

          console.log("File created!");          
          this.fileOpener.open(fileEntry.toURL(), 'application/pdf')
            .then(() => console.log('File is opened'))
            .catch(err => console.error('Error openening file: ' + err));
        })
          .catch((err) => {
            console.error("Error creating file: " + err);
            throw err;  
          });

Thanks in advance.

Upvotes: 5

Views: 12151

Answers (1)

BRass
BRass

Reputation: 3838

In order to SAVE the PDF, you'll need to use some cordova plugins. Ionic has some nice wrappers around these here. Check out the File, File Transfer, and File Opener plugins.

Here's some example code you could use once you get these plugins incorporated into your project:

    var blob = new Blob([res], { type: 'application/pdf' });

    //Determine a native file path to save to
    let filePath = (this.appConfig.isNativeAndroid) ? this.file.externalRootDirectory : this.file.cacheDirectory;

    //Write the file
    this.file.writeFile(filePath, fileName, blob, { replace: true }).then((fileEntry: FileEntry) => {

      console.log("File created!");

      //Open with File Opener plugin
      this.fileOpener.open(fileEntry.toURL(), data.type)
        .then(() => console.log('File is opened'))
        .catch(err => console.error('Error openening file: ' + err));
    })
      .catch((err) => {
        console.error("Error creating file: " + err);
        throw err;  //Rethrow - will be caught by caller
      });

Upvotes: 6

Related Questions