本页内容
打开文档
ComPDFKit PDF SDK for Flutter 提供多种方式打开 PDF 文档,适用于不同使用场景:
- 使用
CPDFReaderWidget
显示内嵌阅读器 UI。 - 使用
ComPDFKit.openDocument()
直接启动完整文档视图。 - 使用
CPDFDocument
进行后台处理或无 UI 操作。
如果您的 PDF 文件存储于 assets 中,需先复制到临时目录再打开。下面是一个通用的资源提取工具方法:
dart
Future<File> extractAsset(BuildContext context, String assetPath,
{bool shouldOverwrite = true, String prefix = ''}) async {
final bytes = await DefaultAssetBundle.of(context).load(assetPath);
final list = bytes.buffer.asUint8List();
final tempDir = await ComPDFKit.getTemporaryDirectory();
final tempDocumentPath = '${tempDir.path}/$prefix$assetPath';
final file = File(tempDocumentPath);
if (shouldOverwrite || !file.existsSync()) {
await file.create(recursive: true);
file.writeAsBytesSync(list);
}
return file;
}
使用 CPDFReaderWidget(推荐内嵌阅读场景)
dart
File document = await extractAsset(context, _documentPath, shouldOverwrite: false);
...
Scaffold(
resizeToAvoidBottomInset: false,
appBar: AppBar(),
body: CPDFReaderWidget(
document: document.path,
configuration: CPDFConfiguration(),
onCreated: (controller) {
},))
...
使用 ComPDFKit.openDocument()(快速跳转阅读器界面)
适合直接打开一个新的阅读界面,快速预览 PDF 文件。
dart
File document = await extractAsset(context, _documentPath);
ComPDFKit.openDocument(document.path, password: '', configuration: CPDFConfiguration());
使用 CPDFDocument(后台处理场景)
适合不需要 UI 的场景,例如文档注释操作、导出导入等。
dart
File document = await extractAsset(context, _documentPath);
// 创建并打开文档
CPDFDocument document = await CPDFDocument.createInstance();
CPDFDocumentError error = await document.open(document.path);
if (error == CPDFDocumentError.success) {
// 使用CPDFDocument对象进行其他操作...
}