This sentence introduces how to compress a PDF document in Java from the following two aspects. • Compress the contents of the document • Compress the image in the document
Compress the contents of the document:
import com.spire.pdf.*;
public class CompressPDF {
public static void main(String[] args) {
String inputFile = "Sample.pdf";
String outputFile = "output/CompressPDFcontent.pdf";
PdfDocument document = new PdfDocument();
document.loadFromFile(inputFile);
document.getFileInfo().setIncrementalUpdate(false);
document.setCompressionLevel(PdfCompressionLevel.Best);
document.saveToFile(outputFile, FileFormat.PDF);
document.close();
}
}
Compress the image in the document
First, it reduces the size of the PDF document by extracting the image of the original PDF document and reducing the image quality to make the image smaller and replacing the reduced image with the image of the original document.
import com.spire.pdf.*;
import com.spire.pdf.exporting.PdfImageInfo;
import com.spire.pdf.graphics.PdfBitmap;
public class CompressPDF {
public static void main(String[] args) {
String inputFile = "Sample.pdf";
String outputFile = "output/CompressPDFImage.pdf";
PdfDocument document = new PdfDocument();
document.loadFromFile(inputFile);
document.getFileInfo().setIncrementalUpdate(false);
for (int i = 0; i < document.getPages().getCount(); i++) {
PdfPageBase page = document.getPages().get(i);
PdfImageInfo[] images = page.getImagesInfo();
if (images != null && images.length > 0)
for (int j = 0; j < images.length; j++) {
PdfImageInfo image = images[j];
PdfBitmap bp = new PdfBitmap(image.getImage());
bp.setQuality(20);
page.replaceImage(j, bp);
}
}
document.saveToFile(outputFile, FileFormat.PDF);
document.close();
}
}
Recommended Posts