Extract Images
ComPDF Flutter SDK provides an image extraction API for exporting embedded images from a PDF document. You can extract images from the whole document or from specific pages.
API Overview
The image extraction API is available on CPDFDocument:
Future<CPDFExtractImageResult> extractImages({
required String directoryPath,
List<int>? pages,
});Parameter description:
| Parameter | Description |
|---|---|
directoryPath | Output directory for extracted images. The SDK writes images directly to this directory. If the directory does not exist, the SDK attempts to create it |
pages | Optional zero-based page indexes. null or an empty list means extracting images from all pages |
The return value is CPDFExtractImageResult:
class CPDFExtractImageResult {
final bool success;
final int count;
final String directoryPath;
final List<String> imagePaths;
}Field description:
| Field | Description |
|---|---|
success | Whether the native image extraction call completed successfully |
count | Number of image files found in directoryPath after extraction |
directoryPath | Output directory for images, the same directory path passed to the API |
imagePaths | Full paths of image files found in directoryPath after extraction |
Output Directory Semantics
directoryPath is the actual output directory specified by the caller. The SDK does not automatically create an extra subdirectory inside it and does not clear the directory.
If you want imagePaths to contain only images generated by the current extraction call, pass a new empty directory or clean the directory in your own business logic before calling the API.
final Directory tempDir = await ComPDFKit.getTemporaryDirectory();
final Directory outputDir = Directory(
'${tempDir.path}/extracted_images_${DateTime.now().millisecondsSinceEpoch}',
);
await outputDir.create(recursive: true);If you reuse an existing directory, the returned imagePaths may include image files that were already in that directory.
Extract Images From All Pages
When pages is not provided, the SDK attempts to extract images from all pages in the document.
import 'dart:io';
import 'package:compdfkit_flutter/compdfkit.dart';
import 'package:compdfkit_flutter/document/cpdf_document.dart';
Future<void> extractAllImages(String filePath) async {
final CPDFDocument document = await CPDFDocument.createInstance();
await document.open(filePath);
final Directory tempDir = await ComPDFKit.getTemporaryDirectory();
final Directory outputDir = Directory(
'${tempDir.path}/extracted_images_${DateTime.now().millisecondsSinceEpoch}',
);
await outputDir.create(recursive: true);
final CPDFExtractImageResult result = await document.extractImages(
directoryPath: outputDir.path,
);
if (result.success) {
print('Image count: ${result.count}');
for (final String imagePath in result.imagePaths) {
print('Image path: $imagePath');
}
} else {
print('Extract images failed.');
}
}Extract Images From Specific Pages
Use the pages parameter to extract images from specific pages only. Page indexes are zero-based.
final CPDFExtractImageResult result = await document.extractImages(
directoryPath: outputDir.path,
pages: [0, 2],
);
print('Extracted image count: ${result.count}');The example above extracts images from page 1 and page 3.
If an invalid page index is passed, such as a negative index or an index greater than or equal to the page count, the API returns a platform error.
Use With CPDFReaderWidget
In a reader page, call the same API through CPDFReaderWidgetController.document.
Future<void> extractImagesFromReader(
CPDFReaderWidgetController controller,
) async {
final Directory tempDir = await ComPDFKit.getTemporaryDirectory();
final Directory outputDir = Directory(
'${tempDir.path}/reader_extracted_images_${DateTime.now().millisecondsSinceEpoch}',
);
await outputDir.create(recursive: true);
final CPDFExtractImageResult result =
await controller.document.extractImages(
directoryPath: outputDir.path,
);
print('Output directory: ${result.directoryPath}');
print('Image count: ${result.count}');
}This is useful when you want to provide image extraction from a custom reader toolbar, menu, or page action.
Display Extracted Images
imagePaths contains local image file paths. You can display them directly with Flutter's Image.file.
GridView.builder(
itemCount: result.imagePaths.length,
gridDelegate: const SliverGridDelegateWithMaxCrossAxisExtent(
maxCrossAxisExtent: 148,
mainAxisSpacing: 10,
crossAxisSpacing: 10,
),
itemBuilder: (context, index) {
return Image.file(
File(result.imagePaths[index]),
fit: BoxFit.contain,
cacheWidth: 320,
);
},
)For full-size preview, combine the image with InteractiveViewer to support zooming.
Complete Example
The following example opens a PDF, creates a new empty output directory, extracts images, and prints the result.
import 'dart:io';
import 'package:compdfkit_flutter/compdfkit.dart';
import 'package:compdfkit_flutter/document/cpdf_document.dart';
Future<List<String>> extractPdfImages(String filePath) async {
final CPDFDocument document = await CPDFDocument.createInstance();
await document.open(filePath);
final Directory tempDir = await ComPDFKit.getTemporaryDirectory();
final Directory outputDir = Directory(
'${tempDir.path}/extract_images_${DateTime.now().millisecondsSinceEpoch}',
);
await outputDir.create(recursive: true);
final CPDFExtractImageResult result = await document.extractImages(
directoryPath: outputDir.path,
);
if (!result.success) {
throw Exception('Extract images failed.');
}
print('Output directory: ${result.directoryPath}');
print('Image count: ${result.count}');
return result.imagePaths;
}Notes
directoryPathmust be a writable local directory path, not a single image file path.- The SDK uses
directoryPathdirectly. It does not automatically create an extra subdirectory and does not clear the directory. - If you need only the images generated by the current extraction call, pass a new empty directory.
pagesuses zero-based page indexes.- If the PDF contains no embedded images, the result may be
success == true,count == 0, andimagePaths.isEmpty == true. - The image format is determined by the PDF embedded image data and the native SDK. Extracted files may be JPEG, PNG, or another supported format.
- Android and iOS have different native return values. The Flutter API uses
CPDFExtractImageResultto provide a unified result structure.