学习Android开发 (Learning Android Development)
The most convenient way for your App to read a provided PDF is to pass it through an intent to an external App as below
吨他为你的应用程序读取PDF提供最便捷的方式是通过一个意图传递给外部应用程序如下
Intent(Intent.ACTION_VIEW).apply {
setDataAndType(pdfPathUri, "application/pdf")
flags = Intent.FLAG_ACTIVITY_CLEAR_TOP
startActivity(this)}
However, that’s limiting because
但是,这是有限制的,因为
- That will assume there’s a PDF reader app in the phone 假设手机中有一个PDF阅读器应用程序
- The user will go out of your app, and might not get back 用户将退出您的应用,并且可能不会回来
- You can’t get to read PDF file in your assets 您无法阅读资产中的PDF文件
So the better way is to show the PDF within your App instead.
因此,更好的方法是改为在您的App中显示PDF。
在ViewPager2中显示PDF (Display PDF in ViewPager2)
Let’s load the PDF in our App instead, ane let’s use the latest and shiniest new ViewPager2 for it in Kotlin as below.
让我们将PDF加载到我们的应用中,如下所示,让我们在Kotlin中使用最新,最闪亮的新ViewPager2。
Here I show you how to extract the PDF file and view it step by step.
在这里,我向您展示如何提取PDF文件并逐步查看它。
It is just simply 2 simple steps as shown above.
如上所示,这只是两个简单的步骤。
1.将文件转换为PdfRenderer (1. Convert File to PdfRenderer)
Beginning Android SDK API 21, it provides us a class PdfRenderer
. We just need to convert the PDF file (either downloaded or from local resources) to it.
从Android SDK API 21开始,它为我们提供了PdfRenderer
类。 我们只需要将PDF文件(下载或从本地资源)转换为它即可。
This can be done by open the file as ParcelFileDescriptior
below, and pass it over to PdfRenderer
.
这可以通过打开下面的ParcelFileDescriptior
文件并将其传递给PdfRenderer
来PdfRenderer
。
private val fileDescriptor = ParcelFileDescriptor.open(
pdfFile, ParcelFileDescriptor.MODE_READ_ONLY)
private val pdfRenderer = PdfRenderer(fileDescriptor)
2.转换器Pdf页面到图像 (2. Converter Pdf Page to Image)
With that, now the pdfRenderer
object will contain the pages of the PDF file within. We can convert a given page to be viewed by
这样,现在pdfRenderer
对象将包含其中的PDF文件页面。 我们可以将给定的页面转换为
By providing the page number, we can use open the pdf page using
pdfRenderer.openPage(pageIndex)
.通过提供页码,我们可以使用
pdfRenderer.openPage(pageIndex)
打开pdf页面。After that, we’ll use
createBitmap
base on thecurrentPage.height
andcurrentPage.width
.之后,我们将基于
currentPage.height
和currentPage.width
使用createBitmap
。Then using
currentPage.render
to render the Bitmap created in above step然后使用
currentPage.render
渲染在上述步骤中创建的位图Send the Bitmap into the given
imageView
将位图发送到给定的
imageView
fun openPage(page: Int, pdfImage: ImageView) {
if (page >= pdfRenderer.pageCount) return
currentPage?.close()
currentPage = pdfRenderer.openPage(page).apply {
val bitmap = Bitmap.createBitmap(
width, height, Bitmap.Config.ARGB_8888)
render(bitmap, null, null,
PdfRenderer.Page.RENDER_MODE_FOR_DISPLAY)
pdfImage.setImageBitmap(bitmap)
}}
翻译自: https://medium.com/mobile-app-development-publication/displaying-pdf-in-viewpager2-f0778eac7aa3