Optimize & compress PDFs on Server/Desktop

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 pdf_doc = new PDFDoc(filename);
2SDFDoc cos_doc = pdf_doc.GetSDFDoc();
3int num_objs = cos_doc.XRefSize();
4for (int i=1; i<num_objs; ++i)
5{
6 Obj obj = cos_doc.GetObj(i);
7 if (obj==null || obj.IsFree() || !obj.IsStream())
8 continue;
9
10 // Process only images
11 DictIterator itr = obj.Find("Subtype");
12 if (!itr.HasNext() || itr.Value().GetName() != "Image")
13 continue;
14
15 pdftron.PDF.Image input_image = new pdftron.PDF.Image(obj);
16
17 // Process only gray-scale images
18 if (input_image.GetComponentNum() != 1)
19 continue;
20
21 int bpc = input_image.GetBitsPerComponent();
22 if (bpc != 1) // Recompress 1 BPC images
23 continue;
24
25 // Skip images that are already compressed using JBIG2
26 itr = obj.Find("Filter");
27 if (itr.HasNext() && itr.Value().IsName() && itr.Value().GetName() == "JBIG2Decode")
28 continue;
29
30 FilterReader reader = new FilterReader(obj.GetDecodedStream());
31
32 ObjSet hint_set = new ObjSet();
33 Obj hint = hint_set.CreateArray();
34 hint.PushBackName("JBIG2");
35 hint.PushBackName("Lossless");
36 hint.PushBackName("Threshold");
37 hint.PushBackNumber(0.4);
38 hint.PushBackName("SharePages");
39 hint.PushBackNumber(10000);
40
41 pdftron.PDF.Image new_image = pdftron.PDF.Image.Create(
42 cos_doc,
43 reader,
44 input_image.GetImageWidth(),
45 input_image.GetImageHeight(),
46 1,
47 ColorSpace.CreateDeviceGray(),
48 hint // A hint to image encoder to use JBIG2 compression
49 );
50 cos_doc.Swap(i, new_image.GetSDFObj().GetObjNum());
51}

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