This brief topic is covers how to compress PDF in Java along with detailed information about complete configuration steps and environment settings including information about necessary classes to be used. You can easily use simple API calls in Java code to reduce PDF file size and save it either on disk or in memory stream. You will see, how you can use different compression options available in OptimizationOptions class to achieve compression.
Steps to Compress PDF in Java
- Add Aspose.PDF for Java library reference from the Maven repository to compress PDF file
- Include the reference to Aspose.PDF namespace in your project to compress PDF
- Create Document class to load the source PDF file
- Instantiate the OptimizationOptions class object to configure the compression of PDF file and set different PDF optimization settings
- Use the optimizeResources method to compress PDF in Java and save PDF on disk
The above example steps in Java reduce PDF size by adopting the defined steps in order. The process will commence by adding API reference using Maven repo and importing required namespaces. We will then load the source PDF file using Document class object to perform compression. In order to set different compression options for PDF, the OptimizationOptions class object will be used. We will set options to compress images and PDF image quality before calling optimizeResources method to apply settings. Finally, the compressed PDF will be saved either on the disk or in memory stream.
Code to Compress PDF in Java
The above example in Java compress PDF size by using few lines of code and simple API interface. The OptimizationOptions is capable of applying different compression settings including LinkDuplicateStreams, RemovePrivateInfo, RemoveUnusedStreams, MaxResolution, ImageEncoding, RemoveUnusedObjects and many other using respective setter methods. Please note that, if the source PDF has a content that can be referred by using above settings, it will contribute towards compression of PDF if the above properties are used.
In this topic, we have seen that in order to develop a PDF compressor Java code can be easily used with the help of simple API calls. If you are interested in splitting PDF to separate pages, refer to the article how to split PDF by pages in Java.