> 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/xamarin/get-started/samples/jbig2test.md).

# JBIGTest

Sample C# code for using Apryse SDK to recompress bitonal (black and white) images in existing PDF documents using JBIG2 compression (lossless or lossy). The sample is intended to show how to specify

Sample C# code for using Apryse SDK to recompress bitonal (black and white) images in existing PDF documents using JBIG2 compression (lossless or lossy). The sample is intended to show how to specify hint information for the image encoder and is not meant to be a generic PDF optimization tool. To demonstrate the possible compression rates, we recompressed a document containing 17 scanned pages. The original input document is \~1.4MB and is using standard CCITT Fax compression. Lossless JBIG2 compression shrunk the filesize to 641KB, while lossy JBIG2 compression shrunk it to 176KB. Learn more about our [Xamarin SDK](/core/get-started/frameworks/dotnet.md).

{% tabs %}
{% tab title="C#" %}
{% code lineNumbers="true" %}

```csharp
//
// Copyright (c) 2001-2021 by PDFTron Systems Inc. All Rights Reserved.
//

using System;
using System.Drawing;
using System.Collections;

using pdftron;
using pdftron.Common;
using pdftron.Filters;
using pdftron.SDF;
using pdftron.PDF;

using NUnit.Framework;

namespace MiscellaneousSamples
{
	/// <summary>
	/// This sample project illustrates how to recompress bi-tonal images in an 
	/// existing PDF document using JBIG2 compression. The sample is not intended 
	/// to be a generic PDF optimization tool.
	/// 
	/// You can download a sample scanned document using the following link:
	///   http://www.pdftron.com/net/samplecode/data/US061222892.pdf
	///
	/// Also a sample page compressed using CCITT Fax compression is located under 
	/// 'PDFNet/Samples/TestFiles' folder.
	/// </summary>
	[TestFixture]
	public class JBIG2Test
	{

		
		/// <summary>
		/// The main entry point for the application.
		/// </summary>
		[Test]
		public static void Sample()
		{
			// Initialize PDFNet before calling any other PDFNet function.

            const string input_path =  "TestFiles/";
            string input_filename = "US061222892-a.pdf";
            
            PDFDoc pdf_doc = new PDFDoc(Utils.GetAssetTempFile(input_path + input_filename));
            pdf_doc.InitSecurityHandler();
			
			SDFDoc cos_doc = pdf_doc.GetSDFDoc();
			int num_objs = cos_doc.XRefSize();

			for (int i=1; i<num_objs; ++i) 
			{
				Obj obj = cos_doc.GetObj(i);
				if (obj!=null && !obj.IsFree()&& obj.IsStream()) 
				{
					// Process only images
					DictIterator itr = obj.Find("Subtype");
					if (!itr.HasNext() || itr.Value().GetName() != "Image") 
						continue; 
					
					pdftron.PDF.Image input_image = new pdftron.PDF.Image(obj);
					pdftron.PDF.Image new_image = null;

					// Process only gray-scale images
					if (input_image.GetComponentNum() != 1) 
						continue; 
					
					int bpc = input_image.GetBitsPerComponent();
					if (bpc != 1) // Recompress 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() == "JBIG2Decode") 
						continue; 

					FilterReader reader = new FilterReader(obj.GetDecodedStream());
					
					ObjSet hint_set = new ObjSet();
					Obj hint = hint_set.CreateArray();
					hint.PushBackName("JBIG2");
					hint.PushBackName("Lossless");
					hint.PushBackName("Threshold");
					hint.PushBackNumber(0.4);
					hint.PushBackName("SharePages");
					hint.PushBackNumber(10000);
					
					new_image = pdftron.PDF.Image.Create(
						cos_doc, 
						reader, 							
						input_image.GetImageWidth(), 
						input_image.GetImageHeight(), 
						1, 
						ColorSpace.CreateDeviceGray(),
						hint  // A hint to image encoder to use JBIG2 compression
						);

					Obj new_img_obj = new_image.GetSDFObj();

					// Copy any important entries from the image dictionary
					itr = obj.Find("ImageMask");
					if (itr.HasNext()) new_img_obj.Put("ImageMask", itr.Value());

					itr = obj.Find("Mask");
					if (itr.HasNext()) new_img_obj.Put("Mask", itr.Value());

					cos_doc.Swap(i, new_image.GetSDFObj().GetObjNum());
				}
			}
			
			pdf_doc.Save(Utils.CreateExternalFile("US061222892_JBIG2.pdf"), SDFDoc.SaveOptions.e_remove_unused);
			pdf_doc.Close();
		}
	}
}
```

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


---

# 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/xamarin/get-started/samples/jbig2test.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.
