在离子中从base64打开pdf [英] open pdf from base64 in ionic

查看:23
本文介绍了在离子中从base64打开pdf的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我有 Jasper 报告,我将其转换为 pdf,然后转换为 REST 控制器中的 base64.如何将其转移到我的 ionic 3 应用程序?我查看了 Ionic Native Document Viewer,但为了做到这一点,我需要将文件传输到应用程序.有什么想法吗?

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?

推荐答案

如果您想在 Ionic 应用中打开 pdf,您必须先将文件保存在本地存储中,然后再打开.基本上你需要两个 Ionic Native 插件和一些 base64 到 blob 转换器:

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:

导入(在组件和 app.module 中)此依赖项:

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,

然后从 REST 服务获取您的 pdf 数据作为 base64(字符串)并执行此函数:

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.opener.open(writeDirectory + filename, 'application/pdf')
            .catch(() => {
                console.log('Error opening pdf file');
            });
    })
    .catch(() => {
        console.error('Error writing pdf file');
    });
}

并将函数从base64转换为blob(需要将文件保存在磁盘上):

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

convertBase64ToBlob(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});
}

这篇关于在离子中从base64打开pdf的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆