> For the complete documentation index, see [llms.txt](https://docs.apryse.com/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.apryse.com/android/optimization/optimize.md).

# Optimize & compress PDFs in Android

Learn how to optimize and compress PDF files with the latest image compression technology. Reduce file size by removing redundant information and compressing data streams. Full code sample included! T

{% hint style="warning" %}
For Android, available in the full version of the library only. See [Apryse full or standard?](/xamarin/get-started/faq/full-vs-standard.md)
{% endhint %}

To optimize a PDF with default settings.

{% tabs %}
{% tab title="Java" %}
{% code lineNumbers="true" %}

```java
PDFDoc doc = new PDFDoc(filename);
Optimizer.optimize(doc);
```

{% endcode %}
{% endtab %}

{% tab title="Kotlin" %}
{% code lineNumbers="true" %}

```kotlin
val doc = PDFDoc(filename)
Optimizer.optimize(doc)
```

{% endcode %}
{% endtab %}
{% endtabs %}

[Compress & optimize PDF files](/android/get-started/samples.md#optimizer) 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.

{% tabs %}
{% tab title="Java" %}
{% code lineNumbers="true" %}

```java
PDFDoc doc = new PDFDoc(filename);
SDFDoc cos_doc = pdf_doc.getSDFDoc();
int num_objs = (int) cos_doc.xRefSize();
for (int i = 1; i < num_objs; ++i) {
	Obj obj = cos_doc.getObj(i);
	if (obj == null || obj.isFree() || !obj.isStream())
		continue;

	// Process only images
	DictIterator itr = obj.find("Subtype");
	if (!itr.hasNext() || !itr.value().getName().equals("Image"))
		continue;

	Image input_image = new Image(obj);

	// Process only gray-scale images
	if (input_image.getComponentNum() != 1)
		continue;

	int bpc = input_image.getBitsPerComponent();
	if (bpc != 1)    // Recompress only 1 BPC images
		continue;

	// Skip images that are already compressed using JBIG2
	itr = obj.find("Filter");
	if (itr.hasNext() && itr.value().isName() && !itr.value().getName().equals("JBIG2Decode")) 
		continue;

	Filter filter = obj.getDecodedStream();
	FilterReader reader = new FilterReader(filter);

	ObjSet hint_set = new ObjSet();
	Obj hint = hint_set.createArray(); // A hint to image encoder to use JBIG2 compression
	hint.pushBackName("JBIG2");
	hint.pushBackName("Lossless");

	Image new_image = Image.create(
		cos_doc, reader,
		input_image.getImageWidth(),
		input_image.getImageHeight(), 
		1, 
		ColorSpace.createDeviceGray(), 
		hint
	);
	cos_doc.swap(i, new_img.getSDFDoc().getObjNum());
}
```

{% endcode %}
{% endtab %}

{% tab title="Kotlin" %}
{% code lineNumbers="true" %}

```kotlin
val doc = PDFDoc(filename)
val cos_doc = pdf_doc.sdfDoc
val num_objs = cos_doc.xRefSize().toInt()
for (i in 1 until num_objs) {
	val obj = cos_doc.getObj(i.toLong())
	if (obj == null || obj.isFree || !obj.isStream) 
		continue;

	// Process only images
	var itr = obj.find("Subtype")
	if (!itr.hasNext() || itr.value().name != "Image")
		continue

	val input_image = Image(obj)

	// Process only gray-scale images
	if (input_image.componentNum != 1)
		continue

	val bpc = input_image.bitsPerComponent
	if (bpc != 1)
	// Recompress only 1 BPC images
		continue

	// Skip images that are already compressed using JBIG2
	itr = obj.find("Filter")
	if (itr.hasNext() && itr.value().isName &&
			itr.value().name != "JBIG2Decode")
		continue

	val filter = obj.decodedStream
	val reader = FilterReader(filter)

	val hint_set = ObjSet()
	val hint = hint_set.createArray() // A hint to image encoder to use JBIG2 compression
	hint.pushBackName("JBIG2")
	hint.pushBackName("Lossless")

	val new_image = Image.create(
		cos_doc, reader,
		input_image.imageWidth,
		input_image.imageHeight, 
		1, 
		ColorSpace.createDeviceGray(), 
		hint
	)
	cos_doc.swap(i.toLong(), new_img.sdfDoc.objNum)
}
```

{% endcode %}
{% endtab %}
{% endtabs %}

[PDF image JBIG2 compression](/android/get-started/samples.md#jbigtest) Full sample code which illustrates how to recompress bitonal (black and white) images in existing PDF documents using JBIG2 compression.


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

```
GET https://docs.apryse.com/android/optimization/optimize.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
