Skip to content
DemoAPI ReferenceFAQ

PDF Generation Template Editor

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

View on GitHub
React Native Guides Compress

Document Compression and Optimization ​

Use getOptimizeOptions() to obtain native defaults, then call optimizeSaveAsCopy() to save a copy. The example accepts a reader whose document has finished loading and a writable output path.

Configure and Compress ​

ts
import { CPDFReaderView, type CPDFOptimizeOptions }
  from '@compdfkit_pdf_sdk/react_native';

async function compressDocument(reader: CPDFReaderView, outputPath: string) {
  if (!await reader.save()) throw new Error('Failed to save the document');
  const document = reader._pdfDocument;
  const current = await document.getOptimizeOptions();
  const options: CPDFOptimizeOptions = {
    ...current,
    flags: ['compress_images', 'remove_unused_objects',
      'remove_empty_objects', 'optimize_page_content'],
    imageQuality: 60,
    colorImageOptions: { ...current.colorImageOptions, quality: 60 },
    grayscaleImageOptions: { ...current.grayscaleImageOptions, quality: 60 },
    monochromeImageOptions: { ...current.monochromeImageOptions, quality: 60 },
  };
  const result = await document.optimizeSaveAsCopy(
    outputPath, options, false,
    (pageIndex) => console.log('Processed page index', pageIndex),
  );
  if (result.cancelled) return result;
  if (!result.ok) throw new Error('Document compression failed');
  return result;
}

The output path must differ from the source, and its parent directory must exist and be writable. When the task ends, the SDK reloads the reader from its source file. Unsaved edits are lost, so save first. Open the output explicitly after success to view the compressed result.

Optimization Options ​

OptionDescription
flagsString array of optimization operations, such as image compression or unused-object cleanup
imageQualityGlobal image quality, from 1 to 100
colorImageOptions, grayscaleImageOptions, monochromeImageOptionsSeparate settings for color, grayscale, and monochrome images
colorSpaceConvertICC color-space conversion settings

Image recompression requires compress_images. Each image group's quality overrides imageQuality, so set all four quality values together. Quality 100 skips image recompression. Image settings also include upperPpi, targetPpi, blockSize, and compressAlgorithm for downsampling and compression.

Color and grayscale images can use jpeg or jpeg2000; monochrome images can use jbig2. On iOS, flate maps to JPEG 2000 and therefore does not establish lossless behavior across platforms. none and run_length retain the image group's default algorithm on iOS.

Defaults include removal of bookmarks, hidden layers, and JavaScript actions. The example explicitly selects four operations. Review required content before using defaults. For color conversion, pass raw ICC file Base64 without a Data URL prefix in colorSpaceConvert.iccDataBase64; rgbToCmyk specifies the conversion direction.

The third argument, fontSubset, defaults to false. Android applies this save option; iOS ignores it.

Progress, Cancellation, and Failures ​

The progress callback receives a processed page index, not a percentage. The result contains ok, cancelled, pagesProcessed, stepsUs, and saveUs. Durations are in microseconds.

Call the following from a cancel button while the task is running:

ts
import { CPDFReaderView } from '@compdfkit_pdf_sdk/react_native';

async function cancelCompression(reader: CPDFReaderView) {
  await reader._pdfDocument.cancelOptimize();
}

After cancellation, the original compression Promise returns cancelled: true. Do not display cancellation as compression success. Only one task can run per reader; iOS shares compression state across the process, so serialize tasks. Starting another task rejects with OPTIMIZE_ALREADY_RUNNING. Invalid output paths may produce INVALID_OUTPUT_PATH. If OPTIMIZE_RESTORE_FAILED occurs, reopen the document to restore the reader before further operations. Other native failures may also reject the Promise. Catch errors and inspect the result.