[Android] android-pdfview:PDFファイルを表示する(APIレベル20以下)

Android5.0からPdfRendererが追加され、PDFビュアーを作成できるようになりました。Android5.0(APIレベル21)以前の端末に対しては、PDFビュアーを作成するためには、外部ライブラリを利用する必要があります。ここでは、APIレベル20以下の端末に対して、外部ライブラリを使ってPDFを表示させる方法について説明します。
広 告
目次
前提条件
動作確認端末
- Google Nexus 4 – 4.4.4 – API19(エミュレータ)
1. PDFライブラリについて
Android端末で動作するPDFのオープンソースライブラリは以下のようなものがあります。
ここではandroid-pdfviewを使ってPDFを表示する方法について説明します。
2. android-pdfviewをインポートする
build.gradleに以下の記述をすることでAndroid-pdfviewをインポートすることが出来ます。
src/build.gradle
dependencies { … compile 'com.joanzapata.pdfview:android-pdfview:1.0.+@aar' }
3. PDFを表示する
android-pdfview
を使ってPDFを表示させる場合、<com.joanzapata.pdfview.PDFView>
タグを利用します。以下にレイアウトXMLの実装例を示します。
res/layout/activity_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" tools:context=".MainActivity"> <com.joanzapata.pdfview.PDFView android:id="@+id/pdfview" android:layout_width="match_parent" android:layout_height="match_parent"/> </LinearLayout>
次にPDFファイルを読み込む処理について説明します。
読み込むことができるのは、①プロジェクト内のassetsフォルダに配置されたファイル、②端末内部に保存されたファイル、です。ここでは、①プロジェクト内のassetsフォルダに配置されたPDFファイルを読み込む方法について説明します。
まずはプロジェクトにassetsフォルダを作成し、読み込むPDFファイルを配置します。assetsフォルダはapp/src/main
フォルダ配下に作成します。

プロジェクトビューからmainフォルダを選択した状態で、右クリックを押しNew > Directory
を選択し、assetsと入力しOKボタンをクリックします。
assetsフォルダ配下に任意のPDFファイルを配置します。今回はsample.pdf
という名称にしています。
次にPDFファイルを読み込むコードです。以下にPDFを読み込むための実装例を示します。
java/<packagename>/MainActivity.java
import com.joanzapata.pdfview.PDFView; … public class MainActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); final PDFView pdfView = (PDFView) findViewById(R.id.pdfview); pdfView.fromAsset("sample.pdf").load(); } … }
pdfView.fromAsset("sample.pdf").load()
でPDFファイルを読み込んでいます。fromAsset()
メソッドの引数にはassetsフォルダに配置したPDFファイル名を指定します。
アプリを実行すると以下のようになります。


4. ライセンスについて
本ライブラリのライセンスはGithubのページにて以下のように記載されています。
Copyright 2013 Joan Zapata
This file is part of Android-pdfview.
Android-pdfview is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
Android-pdfview is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License along with Android-pdfview. If not, see <http://www.gnu.org/licenses/>.