android 打开pdf文件

来源:互联网 发布:协方差矩阵的svd分解 编辑:程序博客网 时间:2024/04/28 00:37

android 打开pdf的几种方法

Intent传递文件路径, PDFView ,android-debug.aar

intent 传递

  1. Uri path = Uri.fromFile(file);  
  2.     Intent intent = new Intent(Intent.ACTION_VIEW);  
  3.     intent.setDataAndType(path, "application/pdf");  
  4.     intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);  
  5.   
  6.   
  7.      try {  
  8.        startActivity(intent);  
  9.        }catch (ActivityNotFoundException e) {  
  10.       Toast.makeText(this, "No Application Available to View PDF",  
  11.                  Toast.LENGTH_SHORT).show();  
  12.            }  
这样会有个问题是通过第三方app打开 如果用户手机没有装能打开pdf文件的app 这个PDF就无法打开 用户体验不好

PDFView 在之前项目用了一下 通过自己写activity 和PDFView来打开pdf,缺陷打开pdf支持pdf编码不多 好像只支持UTF-8 而且打开界面后前几秒 画面跟打了马赛克一样,模糊

open_pdf.xml文件

  1. <?xml version="1.0"encoding="utf-8"?>
  2. <RelativeLayoutxmlns:android="http://schemas.android.com/apk/res/android"
  3. android:layout_width="match_parent"
  4. android:layout_height="match_parent">
  5. <com.joanzapata.pdfview.PDFView
  6. android:id="@+id/pdfView"
  7. android:layout_width="match_parent"
  8. android:layout_height="match_parent"/>
  9. </RelativeLayout>

java代码
  1. import android.app.Activity;
  2. import android.os.Bundle;
  3. import com.joanzapata.pdfview.PDFView;
  4. import com.joanzapata.pdfview.listener.OnPageChangeListener;
  5. import java.io.File;
  6. public class OpenPDFActivity extends Activity implements OnPageChangeListener {
  7. private PDFView pdfView;
  8. Integer pageNumber = 1;
  9. @Override
  10. protected void onCreate(Bundle savedInstanceState) {
  11. super.onCreate(savedInstanceState);
  12. setContentView(R.layout.open_pdf);
  13. pdfView = (PDFView) findViewById(R.id.pdfView);
  14. String path = getIntent().getStringExtra("PATH");//
  15. File file = new File(path);
  16. display(file, true);
  17. }
  18. private void display(File assetFileName, boolean jumpToFirstPage) {
  19. if (jumpToFirstPage) pageNumber = 1;
  20. pdfView.fromFile(assetFileName)
  21. .defaultPage(pageNumber)
  22. .onPageChange(this)
  23. .showMinimap(false)
  24. .enableSwipe(true)
  25. .load();
  26. }
  27. @Override
  28. public void onPageChanged(int page, int pageCount) {
  29. pageNumber = page;
  30. }
  31. @Override
  32. public void onBackPressed() {
  33. super.onBackPressed();
  34. }
  35. }
通过aar打开 (android studio)

在build.gradle

compile(name: 'android-debug', ext: 'aar')
java代码 
  1. public void skip(String path) {
  2. Intent intent = new Intent();
  3. intent.setClass(getApplicationContext(), MuPDFActivity.class);
  4. intent.setAction("android.intent.action.VIEW");
  5. File file = new File(path);
  6. intent.setData(Uri.fromFile(file));
  7. startActivity(intent);
  8. }
点击下载arr文件

0 0
原创粉丝点击