JPedal provides a tool to optimize PDF content in various ways. The optimizer has the ability to remove unused content from the provided PDF, reducing its file size, and to linearize the output for fast web view. The original file is left untouched by this process unless you overwrite it with the output.
Available optimizations
Each optimization is a value of the PdfOptimizer.Optimization enum. On the command line, pass the name of the optimization prefixed with --.
| Optimization | Command-line flag | Description |
|---|---|---|
REMOVEUNUSEDOBJECTS | --removeUnusedObjects | Remove any unused objects from the PDF and flag them as free in the file’s xref table. |
LINEARIZE | --linearize | Linearize the document for fast web view. This is always done after all other optimizations. |
Optimize a PDF with the Command-Line or another language
Pass the optimizations to perform before the input and output files.
java -cp jpedal.jar org.jpedal.tools.PdfOptimizer --removeUnusedObjects --linearize inputFile outputFile
Optimize a PDF in Java
Static Convenience Methods
//Optimize the give PDF file with all default optimizations
PdfOptimizer.optimizePDF(new File("inputFile.pdf"), new File("outputFile.pdf"));
//Optimize the give PDF file with only the specified optimizations
PdfOptimizer.optimizePDF(new File("inputFile.pdf"), new File("outputFile.pdf"),
List.of(PdfOptimizer.Optimization.REMOVEUNUSEDOBJECTS, PdfOptimizer.Optimization.LINEARIZE));
Note that the default optimizations include LINEARIZE, so the output of the first method will be linearized. To optimize a file without linearizing it, pass a list of optimizations which does not include LINEARIZE.
API Access Methods
As PDFOptimizer gains new ways to optimize a PDF the static method above will include all default options to produce an optimized version of the file.
There may be times when you only want to run a single optimization, this can be achieved by loading a file and running each optimization separately.
final File inputFile = new File("inputFile.pdf");
final File outputFile = new File("outputFile.pdf");
final PdfOptimizer optimizer = new PdfOptimizer();
//Load the file to optimize
optimizer.loadFile(inputFile);
//Optimizations to perform
optimizer.removeUnusedObjects();
//Write optimized PDF to output file
Files.write(outputFile.toPath(), optimizer.getoptimizedFileAsBytes());
//Close current PDF
optimizer.closePDF();
Linearization is not available when using the API access methods, use one of the static methods with PdfOptimizer.Optimization.LINEARIZE instead.