Compress Pdf document : PDF Compress « PDF « Java Tutorial






import java.io.FileOutputStream;
import java.io.IOException;

import com.lowagie.text.Document;
import com.lowagie.text.pdf.PdfReader;
import com.lowagie.text.pdf.PdfStamper;
import com.lowagie.text.pdf.PdfWriter;

public class MainClass {
  public static void main(String[] args) throws Exception {
    PdfReader reader = new PdfReader("1.pdf");
    PdfStamper stamper = new PdfStamper(reader, new FileOutputStream("my.pdf"),PdfWriter.VERSION_1_5);
    stamper.setFullCompression();
    stamper.close();

    reader = new PdfReader("1.pdf");
    stamper = new PdfStamper(reader, new FileOutputStream("myDecompressed.pdf"), '1');
    Document.compress = false;
    int total = reader.getNumberOfPages() + 1;
    for (int i = 1; i < total; i++) {
      reader.setPageContent(i, reader.getPageContent(i));
    }
    stamper.close();

    showFileSize("1.pdf");
    showFileSize("my.pdf");
    showFileSize("myDecompressed.pdf");

  }

  private static void showFileSize(String filename) throws IOException {
    PdfReader reader = new PdfReader(filename);
    System.out.print("Size ");
    System.out.print(filename);
    System.out.print(": ");
    System.out.println(reader.getFileLength());
  }
}








29.6.PDF Compress
29.6.1.Full Compression
29.6.2.Compress Pdf document