Skip to content
全新发布

PDF SDK 与 AI 文档处理

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

Guides

打开文档

ComPDF 支持通过本地路径或 Uri 打开 PDF 文档,也支持创建新的 PDF 文档。

通过本地路径打开文档

如果已获取本地文件的绝对路径,可以直接使用 open(String) 打开文档;加密文档则可以再传入密码。

以下是打开 PDF 文档的示例代码:

java
CPDFDocument document = new CPDFDocument(context);
// 打开文档。
CPDFDocument.PDFDocumentError error = document.open(pdfPath);
if (error == CPDFDocument.PDFDocumentError.PDFDocumentErrorPassword) {
  // 打开加密文档:使用密码打开文档。
  error = document.open(pdfPath, "password");
}
if (error == CPDFDocument.PDFDocumentError.PDFDocumentErrorSuccess) {
  // 文档已成功打开,并且可以对数据进行解析和操作。
} else {
  // 无法打开PDF文件。可参考 API 文件了解具体的错误消息。
}
// 检查文档在打开过程中是否已修复。
if (document.hasRepaired()) {
  // 修复后的文档需要先保存,然后再打开,否则无法保存对修复后文档所做的任何编辑或修改。
  // 执行保存操作。
  ...
}
kotlin
val document = CPDFDocument(context)
var error = document.open(pdfPath)
// 打开文档。
when (error) {
  PDFDocumentError.PDFDocumentErrorPassword -> {
    // 打开加密文档:使用密码打开文档。
    error = document.open(pdfPath, "password")
  }
  PDFDocumentError.PDFDocumentErrorSuccess -> {
    // 文档已成功打开,并且可以对数据进行解析和操作。
  }
  else -> {
    // 无法打开PDF文件。可参考 API 文件了解具体的错误消息。
  }
}
// 检查文档在打开过程中是否已修复。
if (document.hasRepaired()) {
	// 修复后的文档需要先保存,然后再打开,否则无法保存对修复后文档所做的任何编辑或修改。
  // 执行保存操作。
  ...
}

通过 Uri 打开文档

当文档来自系统文件选择器、SAF、Google Drive 或 OneDrive 等场景时,建议使用 open(Uri)open(Uri, String) 打开。

SDK 会根据 Uri 的权限、是否可以解析出绝对路径,以及文件是否为虚拟文件,自动选择以路径方式或流方式打开。

以下是通过 Uri 打开文档的示例代码:

java
Uri uri = ...;
CPDFDocument document = new CPDFDocument(context);
CPDFDocument.PDFDocumentError error = document.open(uri);
if (error == CPDFDocument.PDFDocumentError.PDFDocumentErrorPassword) {
  error = document.open(uri, "password");
}
kotlin
val uri: Uri = ...
val document = CPDFDocument(context)
var error = document.open(uri)
if (error == PDFDocumentError.PDFDocumentErrorPassword) {
  error = document.open(uri, "password")
}

如果文档可编辑,SDK 会优先保留可写能力;如果文档只能以流方式打开,则后续保存时需要按流式保存的方式处理。

创建 PDF 文档

以下是创建 PDF 文档的示例代码:

java
CPDFDocument document = CPDFDocument.createDocument(context);
kotlin
val document = CPDFDocument.createDocument(context)

默认创建的新文档不包含任何页面,需要参阅”文档编辑“功能了解如何创建新页面,以及向文档中加入现有页面的详细信息。

打开文档状态说明

以下是打开文档时的状态及其说明:

错误码描述
PDFDocumentErrorSuccess成功打开文档。
PDFDocumentErrorUnknown未知错误。
PDFDocumentErrorFile文件未找到或者不能被打开。
PDFDocumentErrorFormat文件不是 PDF 格式或已损坏。
PDFDocumentErrorPassword需要密码或密码不正确。
PDFDocumentErrorSecurity不支持的安全方案。
PDFDocumentErrorPage页面未找到或内容错误。
PDFDocumentNotVerifyLicense许可证不允许该权限。
PDFDocumentErrorNoReadPermission没有阅读权限