I am using Ionic 4, Capacitor and pdfMake to generate a pdf and open on an android emulator. Since the Capacitor file write does not support blob I am sending it as base64.
Note: I tried using a Cordova plugin to save as a blob but it doesn't work properly with capacitor. Also I have the solution working fine in a Cordova only project but I need to use Capacitor.
However when I open the pdf on the device it says it is in an invalid format. Any ideas what I am doing wrong here?
if (this.plt.is('cordova')) {
this.pdfObj.getBase64((data) => {
this.pdfBase64 = data;
console.log(this.pdfBase64);
});
downloadPdf() {
const { Filesystem } = Plugins;
if (this.plt.is('cordova')) {
console.log('3');
// Save the PDF to the data Directory of our App
const fileName = 'defectreport.pdf';
try {
Filesystem.writeFile({
path: fileName,
data: this.pdfBase64,
directory: FilesystemDirectory.Data,
encoding: FilesystemEncoding.ASCII
}).then((writeFileResult) => {
console.log('File Written');
Filesystem.getUri({
directory: FilesystemDirectory.Data,
path: fileName
}).then((getUriResult) => {
console.log(getUriResult);
const path = getUriResult.uri;
this.fileOpener.open(path, 'application/pdf')
.then(() => console.log('File is opened'))
.catch(error => console.log('Error openening file', error));
}, (error) => {
console.log(error);
});
});
console.log('writeFile complete');
} catch (error) {
console.error('Unable to write file', error);
}
The documentation for the Capacitor fileSystem is misleading. If you pass the encoding parameter to Filesystem.writeFile it assumes that it is a plain text file. If you do not provide it it assumes base64. The code below works.
Filesystem.writeFile({
path: fileName,
data: this.pdfBase64,
directory: FilesystemDirectory.Documents