Optimize & compress PDFs on Server/Desktop

To optimize a PDF with default settings is quick once you are set up.

1doc = PDFDoc.new(filename)
2Optimizer.Optimize(doc)

Compress & optimize PDF files - Full Sample
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. Samples available in Python, C# (.Net), C++, Go, Java, Node.js (JavaScript), PHP, Ruby, VB.

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.

1doc = PDFDoc.new(filename)
2cos_doc = pdf_doc.GetSDFDoc
3num_objs = cos_doc.XRefSize
4i = 1
5while i < num_objs do
6 obj = cos_doc.GetObj(i)
7 if obj.nil? or obj.IsFree or !obj.IsStream
8 i = i + 1
9 next
10 end
11
12 # Process only images
13 itr = obj.Find("Subtype")
14 if !itr.HasNext or !itr.Value.GetName == "Image"
15 i = i + 1
16 next
17 end
18
19 input_image = Image.new(obj)
20
21 # Process only gray-scale images
22 if input_image.GetComponentNum != 1
23 i = i + 1
24 next
25 end
26
27 # Skip images that are already compressed using JBIG2
28 itr = obj.Find("Filter")
29 if itr.HasNext and itr.Value.IsName and itr.Value.GetName == "JBIG2Decode"
30 i = i + 1
31 next
32 end
33
34 filter = obj.GetDecodedStream
35 reader = FilterReader.new(filter)
36
37 hint_set = ObjSet.new # hint to image encoder to use JBIG2 compression
38 hint = hint_set.CreateArray
39
40 hint.PushBackName("JBIG2")
41 hint.PushBackName("Lossless")
42
43 new_image = Image.Create(
44 cos_doc,
45 reader,
46 input_image.GetImageWidth,
47 input_image.GetImageHeight,
48 1,
49 ColorSpace.CreateDeviceGray,
50 hint
51 )
52 cos_doc.Swap(i, new_img.GetSDFDoc.GetObjNum)
53 i = i + 1
54end

PDF image JBIG2 compression - Full Sample
Full sample code which illustrates how to recompress bitonal (black and white) images in existing PDF documents using JBIG2 compression. Samples available in Python, C# (.Net), C++, Go, Java, Node.js (JavaScript), PHP, Ruby, VB.

Did you find this helpful?

Trial setup questions?

Ask experts on Discord

Need other help?

Contact Support

Pricing or product questions?

Contact Sales