android 打开pdf的几种方法
Intent传递文件路径, PDFView ,android-debug.aar
intent 传递
- Uri path = Uri.fromFile(file);
- Intent intent = new Intent(Intent.ACTION_VIEW);
- intent.setDataAndType(path, "application/pdf");
- intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
- try {
- startActivity(intent);
- }catch (ActivityNotFoundException e) {
- Toast.makeText(this, "No Application Available to View PDF",
- Toast.LENGTH_SHORT).show();
- }
PDFView 在之前项目用了一下 通过自己写activity 和PDFView来打开pdf,缺陷打开pdf支持pdf编码不多 好像只支持UTF-8 而且打开界面后前几秒 画面跟打了马赛克一样,模糊
open_pdf.xml文件
- <?xml version="1.0"encoding="utf-8"?>
- <RelativeLayoutxmlns:android="http://schemas.android.com/apk/res/android"
- android:layout_width="match_parent"
- android:layout_height="match_parent">
- <com.joanzapata.pdfview.PDFView
- android:id="@+id/pdfView"
- android:layout_width="match_parent"
- android:layout_height="match_parent"/>
- </RelativeLayout>
java代码
通过aar打开 (android studio)
- import android.app.Activity;
- import android.os.Bundle;
- import com.joanzapata.pdfview.PDFView;
- import com.joanzapata.pdfview.listener.OnPageChangeListener;
- import java.io.File;
- public class OpenPDFActivity extends Activity implements OnPageChangeListener {
- private PDFView pdfView;
- Integer pageNumber = 1;
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.open_pdf);
- pdfView = (PDFView) findViewById(R.id.pdfView);
- String path = getIntent().getStringExtra("PATH");//
- File file = new File(path);
- display(file, true);
- }
- private void display(File assetFileName, boolean jumpToFirstPage) {
- if (jumpToFirstPage) pageNumber = 1;
- pdfView.fromFile(assetFileName)
- .defaultPage(pageNumber)
- .onPageChange(this)
- .showMinimap(false)
- .enableSwipe(true)
- .load();
- }
- @Override
- public void onPageChanged(int page, int pageCount) {
- pageNumber = page;
- }
- @Override
- public void onBackPressed() {
- super.onBackPressed();
- }
- }
在build.gradle
compile(name: 'android-debug', ext: 'aar')
java代码
点击下载arr文件
- public void skip(String path) {
- Intent intent = new Intent();
- intent.setClass(getApplicationContext(), MuPDFActivity.class);
- intent.setAction("android.intent.action.VIEW");
- File file = new File(path);
- intent.setData(Uri.fromFile(file));
- startActivity(intent);
- }