open pdf from base64 in ionic

ぐ巨炮叔叔 提交于 2019-12-11 14:11:25

问题


So I have Jasper reports that I convert to pdf, then to base64 in a REST controller. How do I go about transferring this to my ionic 3 app? I've looked into the Ionic Native Document Viewer, but in order to do this, I would need to transfer the file to the app. Any thoughts?


回答1:


If you like to open pdf in Ionic app you have to first save file in local storage and then open it. Basically you need two Ionic Native plugins and some base64 to blob converter:

Import (in component and in app.module) this dependencies:

https://ionicframework.com/docs/native/file-opener/

https://ionicframework.com/docs/native/file/

Next inject in your components constructor:

private opener: FileOpener,
private file: File,

then get your pdf data from REST service as base64 (string) and execute this function:

saveAndOpenPdf(pdf: string, filename: string) {
  const writeDirectory = this.platform.is('ios') ? this.file.dataDirectory : this.file.externalDataDirectory;
  this.file.writeFile(writeDirectory, filename, this.convertBase64ToBlob(pdf, 'data:application/pdf;base64'), {replace: true})
    .then(() => {
        this.loading.dismiss();
        this.opener.open(writeDirectory + filename, 'application/pdf')
            .catch(() => {
                console.log('Error opening pdf file');
                this.loading.dismiss();
            });
    })
    .catch(() => {
        console.error('Error writing pdf file');
        this.loading.dismiss();
    });
}

And convert function from base64 to blob (need for saving file on disk):

convertBaseb64ToBlob(b64Data, contentType): Blob {
    contentType = contentType || '';
    const sliceSize = 512;
    b64Data = b64Data.replace(/^[^,]+,/, '');
    b64Data = b64Data.replace(/\s/g, '');
    const byteCharacters = window.atob(b64Data);
    const byteArrays = [];
    for (let offset = 0; offset < byteCharacters.length; offset += sliceSize) {
         const slice = byteCharacters.slice(offset, offset + sliceSize);
         const byteNumbers = new Array(slice.length);
         for (let i = 0; i < slice.length; i++) {
             byteNumbers[i] = slice.charCodeAt(i);
         }
         const byteArray = new Uint8Array(byteNumbers);
         byteArrays.push(byteArray);
    }
   return new Blob(byteArrays, {type: contentType});
}


来源:https://stackoverflow.com/questions/49134592/open-pdf-from-base64-in-ionic

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!