Android查看PDF文件

前言

之前使用WebView调用pdf.js加载PDF,效果还不错,但是最近遇到有的平板的WebView渲染的位置偏移很大,所以这里找一下替代方案。

AndroidPdfViewer

AndroidPdfViewer算是比较主流的PDF查看组件,GitHub 星数 8.4k

DImuthuUpe/AndroidPdfViewer: Android view for displaying PDFs rendered with PdfiumAndroid

添加依赖

1
2
// 最新版需迁移到mavenCentral
implementation 'com.github.barteksc:android-pdf-viewer:3.2.0-beta.1'

XML中引用

1
2
3
4
5
<!-- 布局中添加PDFView -->
<com.github.barteksc.pdfviewer.PDFView
android:id="@+id/pdfView"
android:layout_width="match_parent"
android:layout_height="match_parent"/>

加载PDF

1
2
3
4
5
6
7
8
9
fun showPdf(pdffile: File) {
binding.pdfView // 本地文件
.fromFile(pdffile) // 网络/ContentUri
.enableSwipe(true) // 允许滑动翻页
.swipeHorizontal(false) // 垂直/水平翻页
.enableDoubletap(false) // 双击缩放
.defaultPage(0) // 默认显示第0页
.load()
}

注意

该组件加载PDF必须是本地文件,所以我们可以先下载到本地,再调用预览。

显示页码

方法

1
2
3
4
5
6
7
8
9
10
11
12
13
fun showPdf(pdffile: File) {
binding.pdfView
.fromFile(pdffile)
.enableSwipe(true) // 允许滑动翻页
.swipeHorizontal(false) // 垂直/水平翻页
.enableDoubletap(false) // 双击缩放
.defaultPage(0) // 默认显示第0页
.onPageChange {
page, pageCount ->
binding.tvPageIndicator.text = "${page + 1} / $pageCount"
}
.load()
}

XML

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
<FrameLayout
android:layout_width="match_parent"
android:layout_height="match_parent">

<com.github.barteksc.pdfviewer.PDFView
android:id="@+id/pdfView"
android:layout_width="match_parent"
android:layout_height="match_parent" />


<TextView
android:id="@+id/tvPageIndicator"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom|end"
android:paddingTop="2dp"
android:paddingBottom="2dp"
android:paddingStart="5dp"
android:paddingEnd="6dp"
android:layout_margin="4dp"
android:textColor="#999999"
android:textSize="14sp" />

</FrameLayout>