无法在Ionic App中查看本地PDF文件(使用ng2-pdf-viewer)

时间:2018-05-09 14:02:13

标签: android ionic-framework npm ionic3

我正在尝试使用ng2-pdf-viewer npm包在离子应用中查看pdf文件。

使用命令ionic serve

在浏览器上正常工作

使用命令ionic cordova run android -l -c --debug

在调试模式下运行设备时,它也可以正常工作

但是当我使用ionic cordova build android创建一个android版本时,然后尝试查看pdf文件。它出现以下错误

  

UnknowErrorException:无法获取

1 个答案:

答案 0 :(得分:0)

这就是你可以做到的

首先您需要将pdf文件转换为Base64字符串

您可以使用 ionic native File 插件

import { File } from '@ionic-native/file';


pdflink:any;
constructor( private file: File){
    this.fileToBase64("myFile.pdf", "file:///data/user/0/com.xxx.xxx/files")
    }

将 PDF 文件转换为 Base64 字符串

async  fileToBase64(filename, filepath){
            let base64String =  await this.file.readAsDataURL(filepath, filename);
            this.pdfurl=base64String.slice(28);
      this.Base64toArrayBuffer() 
            }

将 Base64 字符串转换为 ArrayBuffer

  Base64toArrayBuffer(){
        var binary_string = window.atob(this.pdfurl);
          var len = binary_string.length;
          var bytes = new Uint8Array(len);
          for (var i = 0; i < len; i++) {
              bytes[i] = binary_string.charCodeAt(i);
          }
         this.pdflink= bytes.buffer;
    }

HTML 代码

 <pdf-viewer [src]="pdflink" style="display: block;" render-text-mode="0" [render-text]="true" [page]="currentpage" [show-all]="false" (after-load-complete)="afterLoadComplete($event)"></pdf-viewer>