所以我有Jasper报告我转换为pdf,然后转换为REST64控制器中的base64。我如何将其转移到我的离子3应用程序?我已经查看了Ionic Native Document Viewer,但为了做到这一点,我需要将文件传输到应用程序。有什么想法吗?
答案 0 :(得分:3)
如果您想在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.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();
});
}
将函数从base64转换为blob(需要在磁盘上保存文件):
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});
}