项目有一个需求,就是在ionic框架里打开pdf文件,因为用inappbrowser插件传入pdf地址的话,会先下载pdf文件,再用本地的pdf阅读器打开,很不方便,所以在stackoverflow搜了半天,没有比较好的方案,只能硬着头皮自己做了(吐槽:国内ionic好像还不是很火,基本上都是以个人开发着玩的为主,我现在遇到问题,已经直接放弃百度,直接找stackoverflow了。。。)
首先,国外还是有用原生ionic直接打开pdf的,传送门。我也依照这个做了一个版本,其中有一个坑,就是我们的需求是打开远端服务器保存的pdf,传递的都是pdf文件的url地址,但是这个作者只是简单的说了一下可以传入url地址,但是具体使用的时候,根本打不开pdf,最终我在stackoverflow里找到解决方案了(感谢stackoverflow里的各路大神。。。)
传送门的这个例子,首先必须要把pdf文件转化成BASE64码的形式传递过来,我就贴一下我解决坑的关键代码,其他的可以参考传送门链接的例子,
var raw = window.atob(decode);//decode就是pdf文件通过base64编码后再经过urldecode转过的一串字符
var rawLength = raw.length;
var array = new Uint8Array(new ArrayBuffer(rawLength));
for(var i = 0; i < rawLength; i++) {
array[i] = raw.charCodeAt(i);
}
$scope.pdfUrl = URL.createObjectURL(new Blob([array], {type: 'application/pdf'}));
在controller里有如上的$scope.pdfurl,就可以用传送门里介绍的方法,打开pdf了,这里就不在赘述,自己看一下他的demo吧。
这里说一下这个方案的优缺点,优点就是这个是跨平台的解决方案,在android和ios都能以同样的方式,在app内部打开pdf进行查看,缺点就是不能用常用的两个手指缩放pdf文件,还有就是,很卡。。。。。。
最终还是放弃这个方案,用native方式实现,这样就得自己写插件了,我实现了一个简单的查看pdf的插件,还有一个是打开原生activity的插件,都放在github上了,写的都比较简单,只是给大家提供一个思路,大家可以下载下来,按照自己的业务需求自己改动,也欢迎在github上提交issue和修改代码。