Search code examples
angulartypescriptionic3cordova-pluginsionic-native

Error: Uncaught (in promise): [object Object] with Ionic native file plugin


I need to create a pdf using blob and I have followed this blog. But it is not working. Can you tell me why?

Note: Error emits on this line const fileEntry = await. This is on the android device. On the browser, it is working fine (i.e. this.pdfObj.download();).

  constructor(
    private file: File,
    private platform: Platform,
    private fileOpener: FileOpener,
  ) {
  }

downloadReport() {
    this.createPdf();
    if (this.platform.is('cordova')) {
      try {
        this.pdfObj.getBuffer(async (buffer) => {
          var utf8=new Uint8Array(buffer);
          var binaryArray=utf8.buffer;
          var blob = new Blob([binaryArray], { type: 'application/pdf' });

          const fileEntry = await this.file.writeFile(this.file.dataDirectory, 'myletter.pdf', blob, { replace: true });
          this.fileOpener.open(this.file.dataDirectory + 'myletter.pdf', 'application/pdf');
        });
      }
      catch (err) {
        console.log(err);
      }

    } else {
      // On a browser simply use download!
      this.pdfObj.download();
    }
  }  



createPdf() {
    var docDefinition = {
      content: [
        { text: 'REMINDER', style: 'header' },
        { text: new Date().toTimeString(), alignment: 'right' },

        { text: 'From', style: 'subheader' }, { text: 'from' },

        { text: 'To', style: 'subheader' }, 'To',

        { text: 'Sam lokuge', style: 'story', margin: [0, 20, 0, 20] },

        {
          ul: [
            'Bacon',
            'Rips',
            'BBQ',
          ]
        }
      ],
      styles: {
        header: {
          fontSize: 18,
          bold: true,
        },
        subheader: {
          fontSize: 14,
          bold: true,
          margin: [0, 15, 0, 0]
        },
        story: {
          italic: true,
          alignment: 'center',
          width: '50%',
        }
      }
    }
    this.pdfObj = pdfMake.createPdf(docDefinition);
  }

This is the error:

 core.js:1350 ERROR Error: Uncaught (in promise): [object Object]
        at c (polyfills.js:3)
        at polyfills.js:3
        at rejected (assessment-report.module.ts:13)
        at t.invoke (polyfills.js:3)
        at Object.onInvoke (core.js:4629)
        at t.invoke (polyfills.js:3)
        at r.run (polyfills.js:3)
        at polyfills.js:3
        at t.invokeTask (polyfills.js:3)
        at Object.onInvokeTask (core.js:4620)

Solution

  • I have found the issue here. That was due to this path this.file.dataDirectory. But the error message was not clearly mentioned about that. So it took a lot of time to identify the issue. Finally, I have changed the path and then no issues. I have used this path this.file.externalApplicationStorageDirectory and now it is working fine.