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.
Starting with 3.2.0, ComPDF Flutter SDK supports optimizing PDFs and saving the results as copies. Use CPDFDocument to configure optimization steps, image quality, and resolution, receive progress updates, or cancel a task.
In these examples, document is an opened CPDFDocument.
import 'package:compdfkit_flutter/compdfkit.dart';After optimization, the SDK reopens the current document from its source file. Save changes you need to retain before starting.
final saved = await document.save();
if (!saved) {
throw StateError('Save the document before optimization.');
}
final current = await document.getOptimizeOptions();
final options = current.copyWith(
flags: {
CPDFOptimizeFlag.removeUnusedObjects,
CPDFOptimizeFlag.removeEmptyObjects,
CPDFOptimizeFlag.compressImages,
CPDFOptimizeFlag.optimizePageContent,
},
imageQuality: 60,
);
try {
final result = await document.optimizeToFile(
'/path/to/optimized.pdf',
options: options,
onProgress: (pageIndex) => print('Processing page $pageIndex'),
);
if (result.cancelled) {
print('Optimization cancelled.');
} else if (result.ok) {
print('Processed ${result.pagesProcessed} pages.');
}
} on CPDFOptimizeException catch (error) {
print('${error.code}: ${error.message}');
}outputPath must be writable, have an existing parent directory, and differ from the current document path. After success, the reader still displays the source document. Open the output file to view the optimized result.
getOptimizeOptions() returns a copy of the native document's current options. Changes do not apply automatically; pass the options to optimizeToFile(options: ...).
| Parameter | Description |
|---|---|
flags | Optimization steps, such as removing unused objects, compressing images, and optimizing page content |
imageQuality | Overall image quality from 0 to 100 |
colorImageOptions | Color image compression and downsampling settings |
grayscaleImageOptions | Grayscale image compression and downsampling settings |
monochromeImageOptions | Monochrome image compression and downsampling settings |
colorSpaceConvert | Optional ICC color space conversion settings |
When CPDFOptimizeFlag.compressImages is enabled, configure each image category separately:
final imageOptions = options.copyWith(
colorImageOptions: options.colorImageOptions.copyWith(
upperPpi: 225,
targetPpi: 150,
quality: 60,
compressAlgorithm: CPDFCompressAlgorithm.jpeg2000,
),
);upperPpi is the resolution threshold for downsampling; targetPpi is the target resolution. quality is the category's image quality from 0 to 100. Pass imageOptions as options on the next optimization call.
The default steps include removing all bookmarks and JavaScript. To retain them, explicitly set flags, as in the initial example. Select options that remove annotations, forms, or embedded fonts according to your workflow. The output is not guaranteed to be smaller than the source.
Use CPDFOptimizeImageOptions.compressAlgorithm to select an algorithm for each image category. blockSize is the encoder's block size and must be greater than 0. You can retain the value returned by getOptimizeOptions().
CPDFCompressAlgorithm | Purpose |
|---|---|
none | Preserve the current image encoding |
flate | Lossless Flate compression |
runLength | Lossless run-length encoding |
jpeg | Lossy JPEG compression |
jpeg2000 | Lossy JPEG 2000 compression |
jbig2 | JBIG2 compression for monochrome images |
Use CPDFColorSpaceConvertOptions to configure RGB and CMYK conversion. iccData accepts the raw bytes of an ICC profile, not a file path. Conversion is disabled when the data is absent or empty.
import 'dart:io';
final iccData = await File('/path/to/profile.icc').readAsBytes();
final colorOptions = options.copyWith(
colorSpaceConvert: CPDFColorSpaceConvertOptions(
iccData: iccData,
rgbToCmyk: true,
),
);
final result = await document.optimizeToFile(
'/path/to/converted.pdf',
options: colorOptions,
);rgbToCmyk: true converts RGB to CMYK; false converts CMYK to RGB. Choose an ICC profile matching the conversion direction and check the output colors. Save changes you need to retain before calling the API.
onProgress reports a zero-based page index, not a percentage. Use the page count to display progress, but wait for the method to return before treating the task as complete.
await document.cancelOptimize();Cancellation is cooperative. The original optimization call resolves with cancelled == true and ok == false; handle this as user cancellation.
CPDFOptimizeResult contains:
| Field | Description |
|---|---|
ok | Whether optimization and output completed successfully |
cancelled | Whether the task ended because of cancellation |
pagesProcessed | Number of processed pages |
stepsUs | Optimization step duration, in microseconds |
saveUs | Output writing duration, in microseconds |
Do not treat output from a cancelled task as a successful result. Duration fields are for statistics and do not represent the entire operation's elapsed time.
Android allows one optimization task per document at a time. iOS allows one task across all documents. Conflicting calls throw OPTIMIZE_ALREADY_RUNNING.
The fontSubset parameter of optimizeToFile() defaults to false. Android can enable font subsetting; iOS uses its native saving behavior.
For invalid paths or settings, check INVALID_OUTPUT_PATH and INVALID_OPTIMIZE_OPTIONS. OPTIMIZE_RESTORE_FAILED means the current document could not be restored from its source. Close and reopen the source document; do not save the document in memory.