Skip to content
全新发布

PDF SDK 与 AI 文档处理

在 GitHub 获取完整的私有化部署SDK 包及 AI 智能文档处理能力,一键部署,快速构建您的文档处理工作流。

Guides

使用 CPDFReaderView

CPDFReaderView 是 ComPDF Android PDF SDK 提供的阅读器视图组件,用于在页面中显示 PDF 文档内容。本页说明最小接入流程,包括布局添加、实例获取以及文档绑定。

适用场景

本页适用于以下场景:

  • 在 Activity 或 Fragment 中嵌入 PDF 阅读器。
  • 打开本地 PDF 文件并显示文档内容。
  • 为后续的加载状态、导航、搜索和模式配置建立基础接入结构。

前置条件

开始接入前,应先确认以下条件已经满足:

  • SDK 集成已经完成。
  • License 已正确配置。
  • 当前页面具备可访问的 PDF 文件路径或文件来源。
  • 页面容器已经准备好承载阅读器视图。

在布局中添加 CPDFReaderView

先在页面布局中添加 CPDFReaderView

xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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"
  tools:context=".MainActivity">

  <com.compdfkit.ui.reader.CPDFReaderView
    android:id="@+id/readerView"
    android:layout_width="match_parent"
    android:layout_height="match_parent" />

</androidx.constraintlayout.widget.ConstraintLayout>

在包含工具栏、底部栏或其他业务区域的页面中,通常建议让 CPDFReaderView 占据主要阅读区域,而不是使用固定尺寸。

获取阅读器实例并打开文档

完成布局添加后,需要依次执行以下步骤:

  1. 获取 CPDFReaderView 实例。
  2. 创建 CPDFDocument
  3. 调用 open(...) 打开文档。
  4. 在文档打开成功后,将文档绑定到 CPDFReaderView

以下示例展示最小可运行接入流程。

java
private CPDFReaderView readerView;
private CPDFDocument document;

@Override
protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);

  readerView = findViewById(R.id.readerView);

  String filePath = "/storage/emulated/0/Download/sample.pdf";
  document = new CPDFDocument(this);

  PDFDocumentError error = document.open(filePath);
  if (error == PDFDocumentError.PDFDocumentErrorSuccess) {
    readerView.setPDFDocument(document);
  } else {
    Log.e("ComPDF", "Open document failed: " + error);
  }
}
kotlin
private lateinit var readerView: CPDFReaderView
private var document: CPDFDocument? = null

override fun onCreate(savedInstanceState: Bundle?) {
  super.onCreate(savedInstanceState)
  setContentView(R.layout.activity_main)

  readerView = findViewById(R.id.readerView)

  val filePath = "/storage/emulated/0/Download/sample.pdf"
  val pdfDocument = CPDFDocument(this)
  val error = pdfDocument.open(filePath)

  if (error == PDFDocumentError.PDFDocumentErrorSuccess) {
    document = pdfDocument
    readerView.setPDFDocument(pdfDocument)
  } else {
    Log.e("ComPDF", "Open document failed: $error")
  }
}

接入顺序说明

CPDFReaderView 仅负责展示文档内容,真正被打开的是 CPDFDocument。因此,正确顺序应为:

  1. 创建 CPDFDocument
  2. 调用 document.open(...)
  3. 判断返回值是否为 PDFDocumentErrorSuccess
  4. 调用 readerView.setPDFDocument(document) 绑定文档。

如果在文档未成功打开前直接绑定到阅读器,页面将无法进入正常显示状态。

常见注意事项

  • open(...) 失败通常与路径无效、文件权限不足、文件损坏或文件来源不可访问有关。
  • 文档来源如果是 Uri、下载目录或沙盒路径,应先确保当前页面具备读取权限。
  • 阅读器成功显示文档后,再继续配置显示模式、导航、搜索、主题等能力,会更容易定位问题。
  • 页面进入正式业务流程后,通常还需要补充文档加载状态与错误处理逻辑。

相关章节