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.
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.
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.
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.
}Configure color, grayscale, and monochrome images with colorImageOptions, grayscaleImageOptions, and monochromeImageOptions, respectively:
| Field | Description |
|---|---|
upperPpi | Downsample images whose resolution exceeds this threshold |
targetPpi | Target resolution, usually below upperPpi |
quality | Lossy image re-encoding quality, from 0 to 100 |
blockSize | Re-encoding block size in pixels |
compressAlgorithm | Algorithm 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.
optimizeFlags is a bit mask. new CPDFOptimizeOptions() includes default cleanup rules; set rules explicitly when particular content must be preserved.
| Example flags | Purpose |
|---|---|
REMOVE_UNUSED_OBJECTS, REMOVE_EMPTY_OBJECTS | Remove unused or empty objects |
REMOVE_INVALID_LINKS, REMOVE_INVALID_BOOKMARKS | Remove invalid navigation data |
REMOVE_ANNOTATIONS, REMOVE_FORMS, REMOVE_FILE_ATTACHMENTS | Remove annotations, forms, or attachments |
REMOVE_HIDDEN_LAYERS, MERGE_VISIBLE_LAYERS | Remove hidden layers or merge visible layers |
REMOVE_DOCUMENT_INFO, REMOVE_METADATA | Remove document information or metadata |
USE_FLATE_FOR_UNCOMPRESSED_STREAMS, REPLACE_LZW_WITH_FLATE | Change stream compression |
REMOVE_EMBEDDED_FONTS | Remove 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:
options.colorSpaceConvert = new CPDFDocument.CPDFColorSpaceConvertOptions(
iccProfileBytes, true); // true: RGB to CMYK; false: CMYK to RGB.An empty iccData disables color conversion.
Use OptimizeListener for progress and cancellation. Set cancelRequested to true when the user requests cancellation:
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.
| Field | Description |
|---|---|
ok / isSuccess() | Whether optimization and saving succeeded |
cancelled / isCancelled() | Whether a cancellation request stopped the operation |
pagesProcessed | Number of processed pages |
stepsUs, saveUs | Optimization and save time in microseconds |
CANNOT_SAVEAS_CURRENTFILE is thrown.fontSubset disable font subsetting by default. Use an overload with that parameter when needed.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.