Java Tutorial/PDF/PDF Compress
Compress Pdf document
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.rupress = 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());
}
}
Full Compression
import java.io.FileOutputStream;
import com.lowagie.text.Document;
import com.lowagie.text.Paragraph;
import com.lowagie.text.pdf.PdfWriter;
public class MainClass {
public static void main(String[] args) throws Exception {
Document document = new Document();
PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream("2.pdf"));
writer.setFullCompression();
document.open();
document.add(new Paragraph("Hello World"));
document.close();
}
}