PDF 生成模板编辑器
开源可视化 PDF 生成引擎,支持自定义模板,并提供面向开发者的 API,灵活构建文档生成流程。
CPDFReaderView 是 ComPDF Android PDF SDK 提供的阅读器视图组件,用于在页面中显示 PDF 文档内容。本页说明最小接入流程,包括布局添加、实例获取以及文档绑定。
本页适用于以下场景:
开始接入前,应先确认以下条件已经满足:
先在页面布局中添加 CPDFReaderView。
<?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 占据主要阅读区域,而不是使用固定尺寸。
完成布局添加后,需要依次执行以下步骤:
CPDFReaderView 实例。CPDFDocument。open(...) 打开文档。CPDFReaderView。以下示例展示最小可运行接入流程。
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);
}
}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。因此,正确顺序应为:
CPDFDocument。document.open(...)。PDFDocumentErrorSuccess。readerView.setPDFDocument(document) 绑定文档。如果在文档未成功打开前直接绑定到阅读器,页面将无法进入正常显示状态。
open(...) 失败通常与路径无效、文件权限不足、文件损坏或文件来源不可访问有关。Uri、下载目录或沙盒路径,应先确保当前页面具备读取权限。