Skip to content
DemoSampleAPI ReferenceFAQ

PDF Generation Template Editor

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

View on GitHub
Android Guides Compress

Compress and Optimize PDF Files ​

Use CPDFDocument.optimizeSaveAsCopy() to configure optimization and write a compressed PDF. The size reduction depends on the document's images and content; text-only files may show little reduction.

Configure and Save an Optimized Copy ​

Here, document is open and outputPath is a writable absolute path different from the source path. Create the output directory first and run the operation on a background thread.

java
import com.compdfkit.core.document.CPDFDocument;
import com.compdfkit.core.document.CPDFDocument.CPDFOptimizeOptions;
import com.compdfkit.core.document.CPDFDocument.CPDFImageOptimizeOptions;
import com.compdfkit.core.document.CPDFDocument.CPDFCompressAlgorithm;
import com.compdfkit.core.document.CPDFDocument.CPDFOptimizeResult;
import com.compdfkit.core.common.CPDFDocumentException;

CPDFOptimizeOptions options = new CPDFOptimizeOptions();
options.optimizeFlags = CPDFOptimizeOptions.COMPRESS_IMAGES
    | CPDFOptimizeOptions.REMOVE_UNUSED_OBJECTS
    | CPDFOptimizeOptions.REMOVE_INVALID_LINKS;
options.colorImageOptions = new CPDFImageOptimizeOptions(
    225, 150, 75, 256, CPDFCompressAlgorithm.kDCT);
options.grayscaleImageOptions = new CPDFImageOptimizeOptions(
    options.colorImageOptions);

try {
    CPDFOptimizeResult result = document.optimizeSaveAsCopy(outputPath, options);
    if (result.isSuccess()) {
        // Output is complete. document is closed; reopen the output to continue reading.
    } else if (result.isCancelled()) {
        // Cancelled. Do not use the incomplete output.
    } else {
        // Optimization or saving failed.
    }
} catch (CPDFDocumentException e) {
    // Check the output path, write access, and whether the source path was used.
}

Image Options ​

Configure color, grayscale, and monochrome images with colorImageOptions, grayscaleImageOptions, and monochromeImageOptions, respectively:

FieldDescription
upperPpiDownsample images whose resolution exceeds this threshold
targetPpiTarget resolution, usually below upperPpi
qualityLossy image re-encoding quality, from 0 to 100
blockSizeRe-encoding block size in pixels
compressAlgorithmAlgorithm enum: kNone, kFlate, kRunLength, kDCT, kJBIG2, kJPX

Select algorithms for each image type, such as kDCT or kJPX for color images and kJBIG2 for monochrome images. The effect of quality depends on the algorithm.

Cleanup and Color Conversion ​

optimizeFlags is a bit mask. new CPDFOptimizeOptions() includes default cleanup rules; set rules explicitly when particular content must be preserved.

Example flagsPurpose
REMOVE_UNUSED_OBJECTS, REMOVE_EMPTY_OBJECTSRemove unused or empty objects
REMOVE_INVALID_LINKS, REMOVE_INVALID_BOOKMARKSRemove invalid navigation data
REMOVE_ANNOTATIONS, REMOVE_FORMS, REMOVE_FILE_ATTACHMENTSRemove annotations, forms, or attachments
REMOVE_HIDDEN_LAYERS, MERGE_VISIBLE_LAYERSRemove hidden layers or merge visible layers
REMOVE_DOCUMENT_INFO, REMOVE_METADATARemove document information or metadata
USE_FLATE_FOR_UNCOMPRESSED_STREAMS, REPLACE_LZW_WITH_FLATEChange stream compression
REMOVE_EMBEDDED_FONTSRemove embedded fonts, which may affect rendering on other devices

Removing content, fonts, or layers changes the output. Choose rules for your requirements and inspect the result. Default rules do not enable REMOVE_EMBEDDED_FONTS.

For RGB/CMYK conversion, supply valid ICC profile bytes for the required conversion:

java
options.colorSpaceConvert = new CPDFDocument.CPDFColorSpaceConvertOptions(
    iccProfileBytes, true); // true: RGB to CMYK; false: CMYK to RGB.

An empty iccData disables color conversion.

Progress and Cancellation ​

Use OptimizeListener for progress and cancellation. Set cancelRequested to true when the user requests cancellation:

java
import java.util.concurrent.atomic.AtomicBoolean;

AtomicBoolean cancelRequested = new AtomicBoolean(false);
CPDFDocument.OptimizeListener listener = new CPDFDocument.OptimizeListener() {
    @Override
    public void onUpdate(int pageIndex) {
        // Current zero-based page index. Switch to the main thread for UI updates.
    }

    @Override
    public boolean isCancelled() {
        return cancelRequested.get();
    }
};

try {
    CPDFOptimizeResult result = document.optimizeSaveAsCopy(
        outputPath, options, false, listener);
    // Handle result.isSuccess(), result.isCancelled(), and failure separately.
} catch (CPDFDocumentException e) {
    // Handle output errors.
}

This is a synchronous operation that polls the listener for cancellation. Do not close or edit the same document while it is being optimized.

Results and Document State ​

FieldDescription
ok / isSuccess()Whether optimization and saving succeeded
cancelled / isCancelled()Whether a cancellation request stopped the operation
pagesProcessedNumber of processed pages
stepsUs, saveUsOptimization and save time in microseconds
  • Success closes the current document. Reopen the output before further operations.
  • Failure or cancellation may leave partial in-memory changes; rollback is not guaranteed. Close the instance and reopen the source to restore its original content.
  • The output path cannot equal the source path; otherwise CANNOT_SAVEAS_CURRENTFILE is thrown.
  • Overloads without fontSubset disable font subsetting by default. Use an overload with that parameter when needed.

Compression Levels ​

The existing saveAsCompressOptimize() method remains available for PDFDocumentCompressLevel presets, with CompressListener for progress. Pass an OptimizeListener for cancellation support. This method also closes the document on success and requires a different output path.

For a ready-made UI, see Tools PDF Compression.