Compress PDF using Java

Compress and reduce a PDF file size by up to 90%

PDF

The Compress PDF Java library by ConvertAPI is a tool that allows for the compression and reduction of PDF file sizes by up to 90%. This Java library optimizes PDF quality by compressing text, graphics, images, subsetting fonts, and optimizing document structure. It offers various parameters for customization, including compression presets, color and grayscale image compression, and options to remove elements like bookmarks, annotations, forms, and embedded files from the PDF. The Java library also provides options for optimizing the PDF for web viewing and preserving the PDF/A standard.

Try for FREE

ConvertAPI Java library install

ConvertAPI provides a Java SDK that allows you to perform a Compress PDF conversion with just a few lines of code. Compress PDF documents using Java programming language with no effort at all!

# Add the following dependency to your pom.xml:
<dependency>
   <groupId>com.convertapi.client</groupId>
   <artifactId>convertapi</artifactId>
   <version>2.10</version>
</dependency>

Authenticate your Java library

You can obtain your secret key by signing up for a free account. Once you sign up, you'll receive 250 free conversions instantly! Grab your authentication secret from the account dashboard, and authenticate the ConvertAPI Java library like this:

# get your secret key here: https://www.convertapi.com/a/auth
use \ConvertApi\ConvertApi;
ConvertApi::setApiSecret('your-api-secret');

Compress PDF using Java in no time!

Once you have your authentication in place, simply copy-paste this pdf to compress conversion code snippet into your Java project:

// Code snippet is using the ConvertAPI JavaScript Client: https://github.com/ConvertAPI/convertapi-js

// Code snippet is using the ConvertAPI Node.js Client: https://github.com/ConvertAPI/convertapi-nodejs

// Code snippet is using the ConvertAPI PHP Client: https://github.com/ConvertAPI/convertapi-php

// Code snippet is using the ConvertAPI Java Client: https://github.com/ConvertAPI/convertapi-java

// Code snippet is using the ConvertAPI C# Client: https://github.com/ConvertAPI/convertapi-dotnet

# Code snippet is using the ConvertAPI Ruby Client: https://github.com/ConvertAPI/convertapi-ruby

# Code snippet is using the ConvertAPI Python Client: https://github.com/ConvertAPI/convertapi-python

// Code snippet is using the ConvertAPI Go Client: https://github.com/ConvertAPI/convertapi-go

REM Code snippet is using the command line utility program: https://github.com/ConvertAPI/convertapi-cli

<!-- For conversions with the multiple file result please refer to this example: https://repl.it/@ConvertAPI/HTML-Form-with-multiple-file-result -->

Upload the file and see how it works

You can set up the advanced conversion parameters and test the conversion result online using our interactive demo tool. It will auto-generate the code snippet for you!


A detailed guide to PDF Compression using Java

Our PDF Compression API can reduce the document size up to 99% of the original while preserving the same visual quality as the original PDF. You can compress your PDF documents with Java using our ConvertAPI library for Java programming language with no effort at all.

PDF compression made easy for Java

Our PDF Compression API reduces document size by optimizing its structure, removing redundant objects, re-encoding images, subsetting fonts, and squeezing the document's size for sharing or long-term storage. It can linearize the document for fast web-view rendering as well as preserve the PDF/A standard. It can also handle password-protected documents. Although our service works via REST API, we have created a wrapper library for Java, so you can compress your PDF documents without writing complex logic and explicit HTTP calls. In this tutorial, we will run through the steps needed to compress PDFs using Java.

How to compress a PDF using Java?

  1. Install the ConvertAPI library for Java
  2. Get your API secret key
  3. Set up the conversion parameters
  4. Copy the auto-generated code snippet

Install ConvertAPI Java library

First, you will need to install our CovnertAPI client library for Java. You can do that using Maven. Simply add the following dependency to your pom.xml file:

<dependency>
    <groupId>com.convertapi.client</groupId>
    <artifactId>convertapi</artifactId>
    <version>2.9</version>
</dependency>

Get your API secret key

Next, you'll want to grab your API secret key. To get the key please sign up for a free ConvertAPI account. You will receive 250 free conversions instantly and will be ready to go!

Get your API secret key

Once you have our library installed and found your secret, set it in the configuration like so:

Config.setDefaultSecret("your-api-secret");

Set up the compression parameters

ConvertAPI is designed to be super simple to implement. You don't even need to code anything - we will get everything done for you. Visit our PDF Compression API page and set up the compression parameters using our live demo tool. Click on the "Advanced properties" and you will see a complete list of parameters to suit your needs. You can test the compression by clicking the "Post" button.

Grab the auto-generated code snippet

Once you are happy with the compression result, you will find the auto-generated code snippet at the bottom of the page! A PDF compression example in Java might look something like this:

Config.setDefaultSecret("your-api-secret");
ConvertApi.convert("pdf", "compress",
    new Param("File", Paths.get("/path/to/sample.pdf")),
    new Param("ColorImageCompression", "jpx"),
    new Param("ColorImageQuality", "70"),
    new Param("ColorImageThresholdDpi", "150"),
    new Param("ColorImageResampleDpi", "100"),
    new Param("RemoveBookmarks", "true"),
    new Param("RemoveAnnotations", "true"),
    new Param("RemoveForms", "true"),
    new Param("RemovePageLabels", "true"),
    new Param("RemoveLayers", "true"),
    new Param("RemoveArticleThreads", "true"),
    new Param("RemoveNamedDestinations", "true"),
    new Param("UnembedBaseFonts", "true"),
    new Param("SubsetEmbeddedFonts", "true"),
    new Param("Linearize", "true")
).get().saveFilesSync(Paths.get("/path/to/result/dir"));

Advanced PDF Compress techniques in Java

As you may already noticed, using our converters is relatively simple. Nevertheless, it provides some more advanced options. For example, our Java library allows you to convert local files, remote files accessible by a URL, or even file streams. Let's see that in action.

Compress a local file

Compressing a local file is the most straightforward way to go. Specify the path of a file from your machine and set the destination folder for the compressed result like so:

Config.setDefaultSecret("your-api-secret");
ConvertApi.convert("pdf", "compress",
    new Param("File", Paths.get("/path/to/my_file.pdf"))
).get().saveFilesSync(Paths.get("/path/to/result/dir"));

Compress a remote file

You can compress a remote file accessible via the URL. Please make sure that the file is publicly accessible (does not require authentication) and is linking to an actual PDF file with the appropriate "application/pdf" content-type header.

Config.setDefaultSecret("your-api-secret");
ConvertApi.convert("pdf", "compress",
    new Param("File", "https://cdn.convertapi.com/cara/testfiles/document-large.pdf")
).get().saveFilesSync(Paths.get("/path/to/result/dir"));

Compress a file stream

To gain the most performance benefits, you might consider working with file streams. To compress a PDF by passing a file stream as a "File" parameter, please have a look at this code example:

Config.setDefaultSecret(getenv("your-api-secret"));

// Creating file data stream
InputStream stream = Files.newInputStream(new File("src/main/resources/sample.pdf").toPath());

System.out.println("Compressing stream of PDF data");
CompletableFuture<ConversionResult> result = ConvertApi.convert("pdf", "compress",
        new Param("file", stream, "sample.pdf")
);

Path pdfFile = Paths.get(System.getProperty("java.io.tmpdir") + "/compressed.pdf");
result.get().saveFile(pdfFile).get();

You can find more useful examples in our GitHub examples folder.

Conclusion

Compressing files with Java is a piece of cake using ConvertAPI, especially when it comes to PDF documents. Our service provides a fully customizable document compression API that can be implemented using Java programming language in a couple of minutes. You can read more about our Java library in our docs. Happy coding!

Advanced Compress PDF conversion parameters

Password String

Sets the password to open protected documents.

Presets Collection

Choose compression level from presets. If preset is selected all other compression options are ignored.

Values:   none text archive web ebook printer

ColorImageCompression Collection

Color image compression algorithm.

Values:   none jpg jpx zip

ColorImageQuality Integer

Color image compression quality. The parameter applies only to JPX and JPG compressions.

ColorImageDownsample Bool

Enable Bicubic image downsampling and decreases the number of pixels in the color image which in turn makes the file smaller.

ColorImageThresholdDpi Integer

Threshold in DPI to activate color images resampling. ColorImageDownsample property must be enabled.

ColorImageResampleDpi Integer

Color image resolution in DPI after Bicubic resampling. ColorImageDownsample property must be enabled.

GrayscaleImageCompression Collection

Grayscale image compression algorithm.

Values:   none jpg jpx zip

GrayscaleImageQuality Integer

Grayscale image compression quality. The parameter applies only to JPX and JPG compressions.

GrayscaleImageDownsample Bool

Enable Bicubic image downsampling and decreases the number of pixels in the grayscale image which in turn makes the file smaller.

GrayscaleImageThresholdDpi Integer

Threshold in DPI to activate grayscale images resampling. GrayscaleImageDownsample property must be enabled.

GrayscaleImageResampleDpi Integer

Grayscale image resolution in DPI after Bicubic resampling. GrayscaleImageDownsample property must be enabled.

MonochromeImageCompression Collection

Monochrome image compression algorithm.

Values:   none jbig2 jbig2l fax zip

MonochromeImageQuality Integer

Monochrome image compression quality. The parameter applies only to jbig2 and jbig2l compressions.

MonochromeImageDownsample Bool

Enable Bicubic image downsampling and decreases the number of pixels in the monochrome image which in turn makes the file smaller.

MonochromeImageThresholdDpi Integer

Threshold in DPI to activate Monochrome images resampling. MonochromeImageDownsample property must be enabled.

MonochromeImageResampleDpi Integer

Monochrome image resolution in DPI after Bicubic resampling. MonochromeImageDownsample property must be enabled.

RemoveBookmarks Bool

Remove bookmarks from the PDF file.

RemoveAnnotations Bool

Remove text annotations from the PDF file.

RemoveForms Bool

Remove PDF forms from the PDF file.

RemovePageLabels Bool

Remove page labels from the PDF file.

RemoveLayers Bool

Removes hidden layers and flatten visible ones.

RemoveArticleThreads Bool

Remove article threads from the PDF file.

RemoveTaggedInfo Bool

Remove tagged information from the PDF file.

RemovePageThumbnails Bool

Remove page thumbnails from the PDF file.

RemoveDuplicates Bool

Remove duplicate fonts and color profiles from the PDF file.

RemoveAlternateImages Bool

Removes alternate images and leave only the one for on-screen viewing.

RemoveNamedDestinations Bool

Remove named destinations from the PDF file.

RemoveEmbeddedFiles Bool

Remove embedded/attachments files from the PDF file.

RemovePieceInformation Bool

Remove piece information dictionaries like Adobe Illustrator or Photoshop private data.

UnembedBaseFonts Bool

Specifies whether to remove the base fonts from the PDF file.

SubsetEmbeddedFonts Bool

Output PDF should only contain font characters utilized in the original document, and any unused glyphs from all fonts in the document should be removed.

CreateObjectStreams Bool

Create object streams in the PDF file. An object stream represents a stream that contains a sequence of PDF objects. This allows a greater number of PDF objects to be compressed. Property compatible with Acrobat 6/PDF v1.5 and later.

Optimize Bool

Optimize page content streams in the PDF file.

LzwToFlate Bool

In streams that use LZW encoding, use Flate instead.

Linearize Bool

Linearize PDF file and optimize for fast Web View.

PreservePdfa Bool

Preserve the PDF/A standard in the PDF file.

Try Compress PDF for free!