Skip to content
DemoFAQ

PDF Generation Template Editor

Open-source visual PDF generation engine with customizable templates and developer-friendly APIs.

View on GitHub
Flutter Guides Compress

Document Compression and Optimization ​

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.

dart
import 'package:compdfkit_flutter/compdfkit.dart';

Compress and Write a Copy ​

After optimization, the SDK reopens the current document from its source file. Save changes you need to retain before starting.

dart
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.

Configure Optimization Options ​

getOptimizeOptions() returns a copy of the native document's current options. Changes do not apply automatically; pass the options to optimizeToFile(options: ...).

ParameterDescription
flagsOptimization steps, such as removing unused objects, compressing images, and optimizing page content
imageQualityOverall image quality from 0 to 100
colorImageOptionsColor image compression and downsampling settings
grayscaleImageOptionsGrayscale image compression and downsampling settings
monochromeImageOptionsMonochrome image compression and downsampling settings
colorSpaceConvertOptional ICC color space conversion settings

When CPDFOptimizeFlag.compressImages is enabled, configure each image category separately:

dart
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.

Image Compression Algorithms ​

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().

CPDFCompressAlgorithmPurpose
nonePreserve the current image encoding
flateLossless Flate compression
runLengthLossless run-length encoding
jpegLossy JPEG compression
jpeg2000Lossy JPEG 2000 compression
jbig2JBIG2 compression for monochrome images

ICC Color Space Conversion ​

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.

dart
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.

Progress and Cancellation ​

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.

dart
await document.cancelOptimize();

Cancellation is cooperative. The original optimization call resolves with cancelled == true and ok == false; handle this as user cancellation.

Read Execution Results ​

CPDFOptimizeResult contains:

FieldDescription
okWhether optimization and output completed successfully
cancelledWhether the task ended because of cancellation
pagesProcessedNumber of processed pages
stepsUsOptimization step duration, in microseconds
saveUsOutput 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.

Platform Differences and Exceptions ​

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.