1. 程式人生 > >Android內部顯示PDF檔案

Android內部顯示PDF檔案

同樣使用網上流行的類庫
1、新增依賴(在你的module中不是project中),新增後別忘記同步

//pdf
compile 'com.github.barteksc:android-pdf-viewer:2.6.1'

2、使用在xml檔案中新增該佈局

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools
="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context="com.mazhan.android_fundfriend.activitys.LoadPDFActivity">
<com.github.barteksc.pdfviewer.PDFView android:id="@+id/pdfView" android:layout_width
="match_parent" android:layout_height="match_parent" />
</LinearLayout>

3、實現

package com.mazhan.android_fundfriend.activitys;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;

import com.github.barteksc.pdfviewer.PDFView;


import
com.github.barteksc.pdfviewer.listener.OnPageChangeListener; import com.mazhan.android_fundfriend.R; import java.io.IOException; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; /** * 顯示PDF的頁面 */ public class LoadPDFActivity extends AppCompatActivity { private static final String TAG = "LoadPDFActivity--TAG:"; private PDFView pdfView; private String path; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_load_pdf); pdfView = findViewById(R.id.pdfView); path = getIntent().getStringExtra("url"); if (!TextUtils.isEmpty(path)) { new LoadPdfThread().start(); } } class LoadPdfThread extends Thread { @Override public void run() { super.run(); try { URL url = new URL(path); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); if (connection.getResponseCode() == 200) { final InputStream inputStream = connection.getInputStream(); //主執行緒更新介面 runOnUiThread(new Runnable() { @Override public void run() { if (inputStream != null) { pdfView.fromStream(inputStream).defaultPage(0)//預設頁面 .enableDoubletap(true) .swipeHorizontal(true)//是不是橫向檢視 .onPageChange(new OnPageChangeListener() { @Override public void onPageChanged(int page, int pageCount) { } }) .enableSwipe(true) .load(); } } }); } } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } } }

我這裡沒有處理記憶體洩露,使用了內部類,而且流沒有關閉,這裡如果直接關閉流,可能導致頁面不顯示