Skip to content
ComPDF
Guides

使用CPDFReaderView

ComPDF SDK 提供了 CPDFReaderView 组件,用于在 Android 应用中 查看和编辑 PDF 文档。本章节将介绍如何在布局中添加该视图并进行初始化。

  1. 在XML布局中添加CPDFReaderView
xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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=".MainActivity">

    <!-- 创建一个 CPDFReaderView -->
    <com.compdfkit.ui.reader.CPDFReaderView
        android:id="@+id/readerview"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</androidx.constraintlayout.widget.ConstraintLayout>
  1. 在代码中获取并初始化视图
java
// 从xml中获取CPDFReaderView
CPDFReaderView readerView = findViewById(R.id.readerview);
  1. 打开PDF文档
java
CPDFDocument document = new CPDFDocument(context);
PDFDocumentError error = document.open("filePath"); // file 或 uri
if (error == PDFDocumentError.PDFDocumentErrorSuccess){
  // 将文档绑定到 CPDFReaderView
  readerView.setPDFDocument(document);
}