Capacitor writeFile - Saving pdf file is in invalid format

If you are using the below (and it is not just a placeholder) you are just sending text as data. Not a pdf.

  1. If you don’t specify an encoding type it assumes it is a base64 string.
  2. You are sending raw text. Not a base64 string. Are you using a pdf generator like pdfMake?

See my code below:

downloadPdf(pdfBase64: string) {
    const { Filesystem } = Plugins;

    if (this.plt.is('cordova')) {
        // Save the PDF to the device
        const fileName = 'defectreport.pdf';
        try {
          Filesystem.writeFile({
            path: fileName,
            data: pdfBase64,
            directory: FilesystemDirectory.Documents
            // encoding: FilesystemEncoding.UTF8
          }).then((writeFileResult) => {
            Filesystem.getUri({
                directory: FilesystemDirectory.Documents,
                path: fileName
            }).then((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);
            });
          });
        } catch (error) {
          console.error('Unable to write file', error);
        }
      } else {
      // On a browser simply use download
      this.defectReportService.getPdfObj().download();
    }
  }
1 Like