Optimize & compress PDFs in Android

For Android, available in the full version of the library only. See Apryse full or standard?

To optimize a PDF with default settings.

1PDFDoc doc = new PDFDoc(filename);
2Optimizer.optimize(doc);

Compress & optimize PDF files
Full code sample which shows how to use 'pdftron.PDF.Optimizer' to reduce PDF file size by removing redundant information and compressing data streams using the latest in image compression technology.

About optimize and compress

Compression as a subset of optimization represents encoding specific data using fewer bits than the original content by reducing the size of the data. This is distinct from optimize (which modifies all images) because you have the ability to choose individual images and to selectively choose the compression type for each.

Apryse SDK supports all basic and advanced compression filters allowed in PDF including:

  • JPEG2000
  • JBIG2
  • CCITT Fax
  • Flate/PNG
  • JPEG/DCT
  • Crypt Filters

Compress images in a PDF document

To compress images using JBIG2 compression inside a PDF.

1PDFDoc doc = new PDFDoc(filename);
2SDFDoc cos_doc = pdf_doc.getSDFDoc();
3int num_objs = (int) cos_doc.xRefSize();
4for (int i = 1; i < num_objs; ++i) {
5 Obj obj = cos_doc.getObj(i);
6 if (obj == null || obj.isFree() || !obj.isStream())
7 continue;
8
9 // Process only images
10 DictIterator itr = obj.find("Subtype");
11 if (!itr.hasNext() || !itr.value().getName().equals("Image"))
12 continue;
13
14 Image input_image = new Image(obj);
15
16 // Process only gray-scale images
17 if (input_image.getComponentNum() != 1)
18 continue;
19
20 int bpc = input_image.getBitsPerComponent();
21 if (bpc != 1) // Recompress only 1 BPC images
22 continue;
23
24 // Skip images that are already compressed using JBIG2
25 itr = obj.find("Filter");
26 if (itr.hasNext() && itr.value().isName() && !itr.value().getName().equals("JBIG2Decode"))
27 continue;
28
29 Filter filter = obj.getDecodedStream();
30 FilterReader reader = new FilterReader(filter);
31
32 ObjSet hint_set = new ObjSet();
33 Obj hint = hint_set.createArray(); // A hint to image encoder to use JBIG2 compression
34 hint.pushBackName("JBIG2");
35 hint.pushBackName("Lossless");
36
37 Image new_image = Image.create(
38 cos_doc, reader,
39 input_image.getImageWidth(),
40 input_image.getImageHeight(),
41 1,
42 ColorSpace.createDeviceGray(),
43 hint
44 );
45 cos_doc.swap(i, new_img.getSDFDoc().getObjNum());
46}

PDF image JBIG2 compression
Full sample code which illustrates how to recompress bitonal (black and white) images in existing PDF documents using JBIG2 compression.

Did you find this helpful?

Trial setup questions?

Ask experts on Discord

Need other help?

Contact Support

Pricing or product questions?

Contact Sales