DEV Community

Gia
Gia

Posted on

How to Compress PDF Files without Loss in Java

PDF file size tends to increase as more contents are embedded in it, such as images and fonts, which may cause longer waiting during uploading or downloading or lead to unstable network connections. To alleviate this issue, we can compress PDF files to improve file transfer efficiency and processing speed. This also can be achieved programmatically. In the following section, I will introduce how to compress PDF files in a Java program. This method mainly reduces file size by compressing unwanted commented lines, white spaces and images in the file, without any loss of other content.

Step 1, Download Free Spire.PDF for Java

Download Free Spire.PDF for Java and unzip it.

It supports creating or editing PDF files independently on Java applications. What’s more, you can also convert PDF to Word, merge PDF files, print PDF files using this library.
By the way, this a community version of Spire.PDF for Java with some limitations on pages during the process. If you want to remove the limitations, please download the commercial product from this link.

Step 2, Create a Project

Create a new Java project.

Step 3, Import JAR File

Import “Spire.Pdf.jar” to project
Take IntelliJ IDEA 2018 (jdk 1.8.0) for example.

  • Click “File”- “Project Structure”- “Modules”- “Dependencies” in turn.
  • Choose the “JARs or Directories” under the green plus.
  • Find the “Spire.Pdf.jar” in the lib folder of the decompressed package and import it to the project.

Step 4, Write Code

You can refer to the sample come below:

import com.spire.pdf.PdfCompressionLevel;
import com.spire.pdf.PdfDocument;
import com.spire.pdf.PdfPageBase;
import com.spire.pdf.exporting.PdfImageInfo;
import com.spire.pdf.graphics.PdfBitmap;

public class CompressPdfDocument {

    public static void main(String[] args) {

        //Create a PdfDocument object
        PdfDocument doc = new PdfDocument();

        //Load a PDF file
        doc.loadFromFile("sample.pdf");

        //Disable incremental update
        doc.getFileInfo().setIncrementalUpdate(false);

        //Set the compression level to best
        doc.setCompressionLevel(PdfCompressionLevel.Best);

        //Loop through the pages in the document
        for (int i = 0; i < doc.getPages().getCount(); i++) {

            //Get a specific page
            PdfPageBase page = doc.getPages().get(i);

            //Get image information collection from the page
            PdfImageInfo[] images = page.getImagesInfo();

            //Traverse the items in the collection
            if (images != null && images.length > 0)
                for (int j = 0; j < images.length; j++) {

                    //Get a specific image
                    PdfImageInfo image = images[j];
                    PdfBitmap bp = new PdfBitmap(image.getImage());

                    //Set the compression quality
                    bp.setQuality(20);

                    //Replace the original image with the compressed one
                    page.replaceImage(j, bp);
                }

            //Save the document to a PDF file
            doc.saveToFile("output/result.pdf");
            doc.close();
        }
    }
}
Enter fullscreen mode Exit fullscreen mode
  • This code starts by creating an object of PdfDocument class and loading a PDF file.
  • Then, disable incremental update using PdfDocument.getFileInfo().setIncrementalUpdate() method and set the compression level to best using PdfDocument.setCompressionLevel() method.
  • Loop through the pages in the document and get the image information collection of each page.
  • Traverse all items in the collection, compress the quality of a specific image using PdfBitmap.setQuality() method, and replace the original image with the compressed one using PdfPageBase.replaceImage() method.
  • Finally, save the result file.

Image description

Top comments (0)