PDF Generation Template Editor
Open-source visual PDF generation engine with customizable templates and developer-friendly APIs.
Open-source visual PDF generation engine with customizable templates and developer-friendly APIs.
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.
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 |
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.
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.');
}
}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.
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.
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.
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;
}directoryPath must be a writable local directory path, not a single image file path.directoryPath directly. It does not automatically create an extra subdirectory and does not clear the directory.pages uses zero-based page indexes.success == true, count == 0, and imagePaths.isEmpty == true.CPDFExtractImageResult to provide a unified result structure.