Some test text!

Discord Logo

Chat with us

PDFTron is now Apryse, learn more here.

Go / Guides / Optimize

Platform


Documentation


PDFTron is now Apryse, learn more here.

Optimize & compress PDFs in Go

To optimize a PDF with default settings.

doc := NewPDFDoc(filename)
OptimizerOptimize(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.

cosDoc := pdfDoc.GetSDFDoc()
numObjs := cosDoc.XRefSize()

i := uint(1)
for i < numObjs{
	obj := cosDoc.GetObj(i)
	if obj != nil && ! obj.IsFree() && obj.IsStream(){
		// Process only images
		itr := obj.Find("Subtype")
		//if not itr.HasNext() or not itr.Value().GetName() == "Image":
		if !itr.HasNext() || !(itr.Value().GetName() == "Image"){
			i = i + 1
			continue
		}
		inputImage := NewImage(obj)
		// Process only gray-scale images
		if inputImage.GetComponentNum() != 1{
			i = i + 1
			continue
		}
		// Skip images that are already compressed using JBIG2
		itr = obj.Find("Filter")
		if (itr.HasNext() && itr.Value().IsName() && itr.Value().GetName() == "JBIG2Decode"){
			i = i + 1
			continue
		}

		filter := obj.GetDecodedStream()
		reader := NewFilterReader(filter)
		
		hintSet := NewObjSet()     // hint to image encoder to use JBIG2 compression
		hint := hintSet.CreateArray()
		
		hint.PushBackName("JBIG2")
		hint.PushBackName("Lossless")
		
		newImage := (ImageCreate(cosDoc, reader, 
											inputImage.GetImageWidth(), 
											inputImage.GetImageHeight(), 
											1, 
											ColorSpaceCreateDeviceGray(), 
											hint))
		
		newImgObj := newImage.GetSDFObj()
		itr = obj.Find("Decode")
		
		if itr.HasNext(){
			newImgObj.Put("Decode", itr.Value())
		}
		itr = obj.Find("ImageMask")
		if itr.HasNext(){
			newImgObj.Put("ImageMask", itr.Value())
		}
		itr = obj.Find("Mask")
		if itr.HasNext(){
			newImgObj.Put("Mask", itr.Value())
		}

		cosDoc.Swap(i, newImgObj.GetObjNum())
	}
	i = i + 1
}

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

Get the answers you need: Support