Android平台下加载PDF文件方案解析

来源:互联网 发布:手机开淘宝店视频教程 编辑:程序博客网 时间:2024/06/06 04:24

第一种方案:

简单粗暴的采用第三方软件加载,也就是说不在当前APP内部打开,而是直接调用第三方APP去查阅PDF文件;

参考核心代码如下:

[html] view plain copy print?在CODE上查看代码片派生到我的代码片
  1. public void openPDFReader(int index) {  
  2.   if (dataList != null && dataList.size() > index) {  
  3.    CoverFlowData tempData = dataList.get(index);  
  4. //   Log.v("wenjianming>>>>>>>>>>", Global.magazinePath+tempData.name+".pdf");  
  5.          File file = new File(Global.magazinePath+tempData.name+".pdf");  
  6.          if (file.exists()) {  
  7.              Uri path = Uri.fromFile(file);  
  8.              Intent intent = new Intent(Intent.ACTION_VIEW);  
  9.              intent.setDataAndType(path, "application/pdf");  
  10.              intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);  
  11.              try {  
  12.                  startActivity(intent);  
  13.              }   
  14.              catch (ActivityNotFoundException e) {  
  15.                  Toast.makeText(ActivityCoverFlow.this,   
  16.                      "No Application Available to View PDF",   
  17.                      Toast.LENGTH_SHORT).show();  
  18.              }  
  19.          }  
  20.   }  



第二种方案:

先赞下iOS平台,加载PDF有各种方案,系统自带API,UIWebView无缝加载显示,可惜Android平台采用简单的WebView加载都是问题,首先因为历史原因,无法连接Google服务器来解析文件,导致方案变得非常被动;

参考核心代码如下:

[html] view plain copy print?在CODE上查看代码片派生到我的代码片
  1. String pdfUrl = "http://www8.cao.go.jp/okinawa/8/2012/0409-1-1.pdf";    
  2. mWebView.loadUrl("http://docs.google.com/gview?embedded=true&url="+ pdfUrl);    


注意:最后一句限制了国内无法在线解析,无奈,友情提示:测试时候先搭建VPN环境;


第三种方案:

采用第三方开源库解析,推荐AndroidPdfViewer(github:https://github.com/barteksc/AndroidPdfViewer),它是基于Google的VuDroid类库来解码PDF文件,在APP内直接加载PDF文件,效果也不错;

参考核心代码如下:


1. 添加类库 build.gradle:

[html] view plain copy print?在CODE上查看代码片派生到我的代码片
  1. compile 'com.github.barteksc:android-pdf-viewer:1.4.0’  

2. 布局文件

[html] view plain copy print?在CODE上查看代码片派生到我的代码片
  1. <com.github.barteksc.pdfviewer.PDFView  
  2.     android:id="@+id/pdfView"  
  3.     android:layout_width="match_parent"  
  4.     android:layout_height="match_parent”/>  


3. 加载代码

[html] view plain copy print?在CODE上查看代码片派生到我的代码片
  1. pdfView = (PDFView) findViewById(R.id.pdfView);  
  2. pdfView.fromAsset(SAMPLE_FILE)  
  3.         .defaultPage(pageNumber)  
  4.         .onPageChange(this)  
  5.         .swipeVertical(true)  
  6.         .showMinimap(false)  
  7.         .enableAnnotationRendering(true)  
  8.         .onLoad(this)  
  9.         .load();  
  10. client = new GoogleApiClient.Builder(this).addApi(AppIndex.API).build();  


4. 下载源码

前往 码农市场免费下载;


转自:http://blog.csdn.net/mapboo/article/details/52170016



0 0
原创粉丝点击