【问题标题】:open pdf from base64 in ionic在离子中从base64打开pdf
【发布时间】:2018-08-14 12:47:07
【问题描述】:

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

【问题讨论】:

    标签: angular pdf ionic3


    【解决方案1】:

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

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

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

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

    接下来注入你的组件构造函数:

    private opener: FileOpener,
    private file: File,
    

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

    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(需要将文件保存在磁盘上):

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

    【讨论】:

    • 如果我将 "this.convertBase64ToBlob(pdf, 'data:application/pdf;base64')" 更改为:"this.convertBase64ToBlob(pdf, 'application/pdf')" 因为新Blob 期望第二个参数是有效的 mimetype 格式
    • 是否可以在不保存实际文件的情况下打开Base64 URL pdf?
    • 我几乎可以肯定你必须先保存它。这里有一些文章供参考:ionicacademy.com/open-pdf-ionic-4
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-09-26
    • 2012-07-17
    • 1970-01-01
    • 2019-05-26
    • 1970-01-01
    • 2017-12-12
    • 1970-01-01
    相关资源
    最近更新 更多