kotlin 显示在线pdf完整示例
时间: 2023-09-30 21:05:29 浏览: 133
在线显示pdf
5星 · 资源好评率100%
以下是一个使用Kotlin显示在线PDF的完整示例:
```kotlin
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.view.View
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import com.github.barteksc.pdfviewer.PDFView
import com.github.barteksc.pdfviewer.listener.OnLoadCompleteListener
import com.github.barteksc.pdfviewer.listener.OnPageChangeListener
import com.github.barteksc.pdfviewer.scroll.DefaultScrollHandle
import com.github.barteksc.pdfviewer.util.FitPolicy
class MainActivity : AppCompatActivity(), OnPageChangeListener, OnLoadCompleteListener {
private lateinit var pdfView: PDFView
private var pageNumber: Int = 0
private var pdfFileName: String? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
pdfView = findViewById(R.id.pdfView)
displayFromUri(Uri.parse("https://www.sample.com/sample.pdf"))
}
private fun displayFromUri(uri: Uri) {
pdfFileName = getFileName(uri)
pdfView.fromUri(uri)
.defaultPage(pageNumber)
.onPageChange(this)
.enableAnnotationRendering(true)
.onLoad(this)
.scrollHandle(DefaultScrollHandle(this))
.spacing(10) // in dp
.pageFitPolicy(FitPolicy.BOTH)
.load()
}
private fun getFileName(uri: Uri): String? {
var result: String? = null
if (uri.scheme == "content") {
val cursor = contentResolver.query(uri, null, null, null, null)
if (cursor != null && cursor.moveToFirst()) {
result = cursor.getString(cursor.getColumnIndexOrThrow("_display_name"))
cursor.close()
}
}
if (result == null) {
result = uri.lastPathSegment
}
return result
}
override fun onPageChanged(page: Int, pageCount: Int) {
pageNumber = page
title = String.format("%s %s / %s", pdfFileName, page + 1, pageCount)
}
override fun loadComplete(nbPages: Int) {
val meta = pdfView.documentMeta
printBookmarksTree(pdfView.tableOfContents, "-")
}
private fun printBookmarksTree(tree: List<com.shockwave.pdfium.treeview.PdfDocument.Bookmark>, sep: String) {
for (b in tree) {
println("$sep ${b.title} ${b.pageIdx}")
if (b.hasChildren()) {
printBookmarksTree(b.children, "$sep-")
}
}
}
fun onDownloadButtonClick(view: View) {
val intent = Intent(Intent.ACTION_VIEW)
intent.data = Uri.parse("https://www.sample.com/sample.pdf")
startActivity(intent)
}
fun onShareButtonClick(view: View) {
val intent = Intent(Intent.ACTION_SEND)
intent.type = "text/plain"
intent.putExtra(Intent.EXTRA_SUBJECT, "Share PDF")
intent.putExtra(Intent.EXTRA_TEXT, "https://www.sample.com/sample.pdf")
startActivity(Intent.createChooser(intent, "Share PDF"))
}
fun onPrintButtonClick(view: View) {
Toast.makeText(this, "Printing PDF...", Toast.LENGTH_SHORT).show()
}
}
```
这个例子中,我们使用了一个名为 `PDFView` 的开源库来显示PDF文件。我们从URI加载PDF文件,然后在PDFView中显示它。我们还添加了一些按钮以便用户可以下载、分享或打印PDF文件。
阅读全文