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.
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
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With