Sample 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. Capabilities include programatically creating new fields and widget annotations, form filling, modifying existing field values, form templating, and flattening form fields.
Learn more about our Server SDK.
1//
2// Copyright (c) 2001-2024 by Apryse Software Inc. All Rights Reserved.
3//
4
5using System;
6using System.Drawing;
7using System.Collections;
8
9using pdftron;
10using pdftron.Common;
11using pdftron.Filters;
12using pdftron.SDF;
13using pdftron.PDF;
14
15namespace JBIG2TestCS
16{
17	/// <summary>
18	/// This sample project illustrates how to recompress bi-tonal images in an 
19	/// existing PDF document using JBIG2 compression. The sample is not intended 
20	/// to be a generic PDF optimization tool.
21	/// 
22	/// You can download a sample scanned document using the following link:
23	///   http://www.pdftron.com/net/samplecode/data/US061222892.pdf
24	///
25	/// Also a sample page compressed using CCITT Fax compression is located under 
26	/// 'PDFNet/Samples/TestFiles' folder.
27	/// </summary>
28	public class Class1
29	{
30
31		private static pdftron.PDFNetLoader pdfNetLoader = pdftron.PDFNetLoader.Instance();
32		static Class1() {}
33		
34		/// <summary>
35		/// The main entry point for the application.
36		/// </summary>
37		static void Main() 
38		{
39			// Initialize PDFNet before calling any other PDFNet function.
40			PDFNet.Initialize(PDFTronLicense.Key);
41
42			string input_path = "../../../../TestFiles/";
43			string output_path = "../../../../TestFiles/Output/";
44			string input_filename = "US061222892-a.pdf";
45			
46			PDFDoc pdf_doc = new PDFDoc(input_path + input_filename);
47			pdf_doc.InitSecurityHandler();
48			
49			SDFDoc cos_doc = pdf_doc.GetSDFDoc();
50			int num_objs = cos_doc.XRefSize();
51
52			for (int i=1; i<num_objs; ++i) 
53			{
54				Obj obj = cos_doc.GetObj(i);
55				if (obj!=null && !obj.IsFree()&& obj.IsStream()) 
56				{
57					// Process only images
58					DictIterator itr = obj.Find("Subtype");
59					if (!itr.HasNext() || itr.Value().GetName() != "Image") 
60						continue; 
61					
62					pdftron.PDF.Image input_image = new pdftron.PDF.Image(obj);
63					pdftron.PDF.Image new_image = null;
64
65					// Process only gray-scale images
66					if (input_image.GetComponentNum() != 1) 
67						continue; 
68					
69					int bpc = input_image.GetBitsPerComponent();
70					if (bpc != 1) // Recompress 1 BPC images
71						continue;
72					
73					// Skip images that are already compressed using JBIG2
74					itr = obj.Find("Filter");
75					if (itr.HasNext() && itr.Value().IsName() && 
76						itr.Value().GetName() == "JBIG2Decode") 
77						continue; 
78
79					FilterReader reader = new FilterReader(obj.GetDecodedStream());
80					
81					ObjSet hint_set = new ObjSet();
82					Obj hint = hint_set.CreateArray();
83					hint.PushBackName("JBIG2");
84					hint.PushBackName("Lossless");
85					hint.PushBackName("Threshold");
86					hint.PushBackNumber(0.4);
87					hint.PushBackName("SharePages");
88					hint.PushBackNumber(10000);
89					
90					new_image = pdftron.PDF.Image.Create(
91						cos_doc, 
92						reader, 							
93						input_image.GetImageWidth(), 
94						input_image.GetImageHeight(), 
95						1, 
96						ColorSpace.CreateDeviceGray(),
97						hint  // A hint to image encoder to use JBIG2 compression
98						);
99
100					Obj new_img_obj = new_image.GetSDFObj();
101
102					// Copy any important entries from the image dictionary
103					itr = obj.Find("ImageMask");
104					if (itr.HasNext()) new_img_obj.Put("ImageMask", itr.Value());
105
106					itr = obj.Find("Mask");
107					if (itr.HasNext()) new_img_obj.Put("Mask", itr.Value());
108
109					cos_doc.Swap(i, new_image.GetSDFObj().GetObjNum());
110				}
111			}
112			
113			pdf_doc.Save(output_path + "US061222892_JBIG2.pdf", SDFDoc.SaveOptions.e_remove_unused);
114			pdf_doc.Close();
115			PDFNet.Terminate();
116		}
117	}
118}
1//---------------------------------------------------------------------------------------
2// Copyright (c) 2001-2024 by Apryse Software Inc. All Rights Reserved.
3// Consult legal.txt regarding legal and license information.
4//---------------------------------------------------------------------------------------
5
6import com.pdftron.filters.Filter;
7import com.pdftron.filters.FilterReader;
8import com.pdftron.pdf.*;
9import com.pdftron.sdf.DictIterator;
10import com.pdftron.sdf.Obj;
11import com.pdftron.sdf.ObjSet;
12import com.pdftron.sdf.SDFDoc;
13
14// This sample project illustrates how to recompress bi-tonal images in an 
15// existing PDF document using JBIG2 compression. The sample is not intended 
16// to be a generic PDF optimization tool.
17//
18// You can download the entire document using the following link:
19//   http://www.pdftron.com/net/samplecode/data/US061222892.pdf
20public class JBIG2Test {
21
22    public static void main(String[] args) {
23        PDFNet.initialize(PDFTronLicense.Key());
24
25        String input_path = "../../TestFiles/";
26        String output_path = "../../TestFiles/Output/";
27
28        try (PDFDoc pdf_doc = new PDFDoc(input_path + "US061222892-a.pdf")) {
29            pdf_doc.initSecurityHandler();
30
31            SDFDoc cos_doc = pdf_doc.getSDFDoc();
32            int num_objs = (int) cos_doc.xRefSize();
33            for (int i = 1; i < num_objs; ++i) {
34                Obj obj = cos_doc.getObj(i);
35                if (obj != null && !obj.isFree() && obj.isStream()) {
36                    // Process only images
37                    DictIterator itr = obj.find("Subtype");
38                    if (!itr.hasNext() || !itr.value().getName().equals("Image"))
39                        continue;
40
41                    Image input_image = new Image(obj);
42                    // Process only gray-scale images
43                    if (input_image.getComponentNum() != 1)
44                        continue;
45                    int bpc = input_image.getBitsPerComponent();
46                    if (bpc != 1)    // Recompress only 1 BPC images
47                        continue;
48
49                    // Skip images that are already compressed using JBIG2
50                    itr = obj.find("Filter");
51                    if (itr.hasNext() && itr.value().isName() &&
52                            !itr.value().getName().equals("JBIG2Decode")) continue;
53
54                    Filter filter = obj.getDecodedStream();
55                    FilterReader reader = new FilterReader(filter);
56
57                    ObjSet hint_set = new ObjSet();
58                    Obj hint = hint_set.createArray(); // A hint to image encoder to use JBIG2 compression
59                    hint.pushBackName("JBIG2");
60                    hint.pushBackName("Lossless");
61
62                    Image new_image = Image.create(cos_doc, reader,
63                            input_image.getImageWidth(),
64                            input_image.getImageHeight(), 1, ColorSpace.createDeviceGray(), hint);
65
66                    Obj new_img_obj = new_image.getSDFObj();
67                    itr = obj.find("Decode");
68                    if (itr.hasNext())
69                        new_img_obj.put("Decode", itr.value());
70                    itr = obj.find("ImageMask");
71                    if (itr.hasNext())
72                        new_img_obj.put("ImageMask", itr.value());
73                    itr = obj.find("Mask");
74                    if (itr.hasNext())
75                        new_img_obj.put("Mask", itr.value());
76
77                    cos_doc.swap(i, new_img_obj.getObjNum());
78                }
79            }
80
81            pdf_doc.save(output_path + "US061222892_JBIG2.pdf", SDFDoc.SaveMode.REMOVE_UNUSED, null);
82        } catch (Exception e) {
83            e.printStackTrace();
84        }
85
86        PDFNet.terminate();
87    }
88
89}
1//---------------------------------------------------------------------------------------
2// Copyright (c) 2001-2021 by PDFTron Systems Inc. All Rights Reserved.
3// Consult LICENSE.txt regarding license information.
4//---------------------------------------------------------------------------------------
5
6package main
7import (
8	. "pdftron"
9)
10
11import  "pdftron/Samples/LicenseKey/GO"
12
13// This sample project illustrates how to recompress bi-tonal images in an 
14// existing PDF document using JBIG2 compression. The sample is not intended 
15// to be a generic PDF optimization tool.
16//
17// You can download the entire document using the following link:
18//   http://www.pdftron.com/net/samplecode/data/US061222892.pdf
19// Relative path to the folder containing the test files.
20var inputPath = "../../TestFiles/"
21var outputPath = "../../TestFiles/Output/"
22
23func main(){
24    PDFNetInitialize(PDFTronLicense.Key)
25    
26    pdfDoc := NewPDFDoc(inputPath + "US061222892-a.pdf")
27    pdfDoc.InitSecurityHandler()
28    
29    cosDoc := pdfDoc.GetSDFDoc()
30    numObjs := cosDoc.XRefSize()
31    
32    i := uint(1)
33    for i < numObjs{
34        obj := cosDoc.GetObj(i)
35        if obj != nil && ! obj.IsFree() && obj.IsStream(){
36            // Process only images
37            itr := obj.Find("Subtype")
38            //if not itr.HasNext() or not itr.Value().GetName() == "Image":
39            if !itr.HasNext() || !(itr.Value().GetName() == "Image"){
40                i = i + 1
41                continue
42            }
43            inputImage := NewImage(obj)
44            // Process only gray-scale images
45            if inputImage.GetComponentNum() != 1{
46                i = i + 1
47                continue
48            }
49            // Skip images that are already compressed using JBIG2
50            itr = obj.Find("Filter")
51            if (itr.HasNext() && itr.Value().IsName() && itr.Value().GetName() == "JBIG2Decode"){
52                i = i + 1
53                continue
54            }
55
56            filter := obj.GetDecodedStream()
57            reader := NewFilterReader(filter)
58            
59            hintSet := NewObjSet()     // hint to image encoder to use JBIG2 compression
60            hint := hintSet.CreateArray()
61            
62            hint.PushBackName("JBIG2")
63            hint.PushBackName("Lossless")
64            
65            newImage := (ImageCreate(cosDoc, reader, 
66                                     inputImage.GetImageWidth(), 
67                                     inputImage.GetImageHeight(), 
68                                     1, 
69                                     ColorSpaceCreateDeviceGray(), 
70                                     hint))
71            
72            newImgObj := newImage.GetSDFObj()
73            itr = obj.Find("Decode")
74            
75            if itr.HasNext(){
76                newImgObj.Put("Decode", itr.Value())
77            }
78            itr = obj.Find("ImageMask")
79            if itr.HasNext(){
80                newImgObj.Put("ImageMask", itr.Value())
81            }
82            itr = obj.Find("Mask")
83            if itr.HasNext(){
84                newImgObj.Put("Mask", itr.Value())
85            }
86
87            cosDoc.Swap(i, newImgObj.GetObjNum())
88        }
89        i = i + 1
90    }
91
92    pdfDoc.Save(outputPath + "US061222892_JBIG2.pdf", uint(SDFDocE_remove_unused))
93    pdfDoc.Close()                
94    PDFNetTerminate()
95}
1//---------------------------------------------------------------------------------------
2// Copyright (c) 2001-2024 by Apryse Software Inc. All Rights Reserved.
3// Consult legal.txt regarding legal and license information.
4//---------------------------------------------------------------------------------------
5
6#include <iostream>
7#include <PDF/PDFNet.h>
8#include <PDF/PDFDoc.h>
9#include <PDF/ElementBuilder.h>
10#include <Filters/FilterReader.h>
11#include <SDF/ObjSet.h>
12#include "../../LicenseKey/CPP/LicenseKey.h"
13
14using namespace std;
15using namespace pdftron;
16using namespace Filters;
17using namespace PDF;
18using namespace SDF;
19using namespace Common;
20
21// This sample project illustrates how to recompress bi-tonal images in an 
22// existing PDF document using JBIG2 compression. The sample is not intended 
23// to be a generic PDF optimization tool.
24//
25// You can download the entire document using the following link:
26//   http://www.pdftron.com/net/samplecode/data/US061222892.pdf
27//
28int main(int argc, char *argv[]) 
29{
30	PDFNet::Initialize(LicenseKey);
31	
32	try 
33	{
34		PDFDoc pdf_doc("../../TestFiles/US061222892-a.pdf");
35		pdf_doc.InitSecurityHandler();
36
37		SDFDoc& cos_doc = pdf_doc.GetSDFDoc();
38		int num_objs = cos_doc.XRefSize();
39		for(int i=1; i<num_objs; ++i) 
40		{
41			Obj obj = cos_doc.GetObj(i);
42			if(obj && !obj.IsFree() && obj.IsStream()) 
43			{
44				// Process only images
45				DictIterator itr = obj.Find("Subtype");
46				if(!itr.HasNext() || strcmp(itr.Value().GetName(), "Image"))
47					continue;
48				
49				Image input_image(obj);
50				// Process only gray-scale images
51				if(input_image.GetComponentNum() != 1)
52					continue;
53				int bpc = input_image.GetBitsPerComponent();
54				if(bpc != 1)	// Recompress only 1 BPC images
55					continue;
56
57				// Skip images that are already compressed using JBIG2
58				itr = obj.Find("Filter");
59				if (itr.HasNext() && itr.Value().IsName() && 
60					!strcmp(itr.Value().GetName(), "JBIG2Decode")) continue; 
61
62				Filter filter=obj.GetDecodedStream();
63				FilterReader reader(filter);
64
65
66				ObjSet hint_set; 	// A hint to image encoder to use JBIG2 compression
67				Obj hint=hint_set.CreateArray();
68			
69				hint.PushBackName("JBIG2");
70				hint.PushBackName("Lossless");
71
72				Image new_image = Image::Create(cos_doc, reader, 
73					input_image.GetImageWidth(), 
74					input_image.GetImageHeight(), 1, ColorSpace::CreateDeviceGray(), hint);
75
76				Obj new_img_obj = new_image.GetSDFObj();
77				itr = obj.Find("Decode");
78				if(itr.HasNext())
79					new_img_obj.Put("Decode", itr.Value());
80				itr = obj.Find("ImageMask");
81				if (itr.HasNext())
82					new_img_obj.Put("ImageMask", itr.Value());
83				itr = obj.Find("Mask");
84				if (itr.HasNext())
85					new_img_obj.Put("Mask", itr.Value());
86
87				cos_doc.Swap(i, new_img_obj.GetObjNum());
88			}
89		}
90
91		pdf_doc.Save("../../TestFiles/Output/US061222892_JBIG2.pdf", SDFDoc::e_remove_unused, 0);
92	}
93	catch(Common::Exception& e)
94	{
95		cout << e << endl;
96		cout << "Please make sure that the pathname to the test file is correct." << endl;
97	}
98	catch(...)
99	{
100		cout << "Unknown Exception" << endl;
101	}
102
103	PDFNet::Terminate();
104	return 0;
105}
1//---------------------------------------------------------------------------------------
2// Copyright (c) 2001-2024 by Apryse Software Inc. All Rights Reserved.
3// Consult legal.txt regarding legal and license information.
4//---------------------------------------------------------------------------------------
5
6
7// This sample project illustrates how to recompress bi-tonal images in an 
8// existing PDF document using JBIG2 compression. The sample is not intended 
9// to be a generic PDF optimization tool.
10//
11// You can download the entire document using the following link:
12//   http://www.pdftron.com/net/samplecode/data/US061222892.pdf
13//
14
15const { PDFNet } = require('@pdftron/pdfnet-node');
16const PDFTronLicense = require('../LicenseKey/LicenseKey');
17
18((exports) => {
19  'use strict';
20
21  exports.runJBIG2Test = () => {
22    const main = async () => {
23      try {
24        const pdf_doc = await PDFNet.PDFDoc.createFromFilePath('../TestFiles/US061222892-a.pdf');
25        pdf_doc.initSecurityHandler();
26
27        const cos_doc = await pdf_doc.getSDFDoc();
28        const num_objs = await cos_doc.xRefSize();
29        for (let i = 1; i < num_objs; ++i) {
30          const obj = await cos_doc.getObj(i);
31          if (obj && !(await obj.isFree()) && await obj.isStream()) {
32            // Process only images
33            let itr = await obj.find('Subtype');
34            if (!(await itr.hasNext()) || await (await itr.value()).getName() !== 'Image')
35              continue;
36            const input_image = await PDFNet.Image.createFromObj(obj);
37            // Process only gray-scale images
38            if (await input_image.getComponentNum() != 1)
39              continue;
40            if (await input_image.getBitsPerComponent() != 1) // Recompress only 1 BPC images
41              continue;
42
43            // Skip images that are already compressed using JBIG2
44            itr = await obj.find('Filter');
45            if (await itr.hasNext()) {
46              const value = await itr.value();
47              if (await value.isName() && await value.getName() === 'JBIG2Decode') continue;
48            }
49
50            const filter = await obj.getDecodedStream();
51            const reader = await PDFNet.FilterReader.create(filter);
52
53            const hint_set = await PDFNet.ObjSet.create();
54            const hint = await hint_set.createArray();
55
56            hint.pushBackName('JBIG2');
57            hint.pushBackName('Lossless');
58
59            const new_image = await PDFNet.Image.createFromStream(cos_doc, reader, await input_image.getImageWidth(),
60              await input_image.getImageHeight(), 1, await PDFNet.ColorSpace.createDeviceGray(), hint);
61
62            const new_img_obj = await new_image.getSDFObj();
63            itr = await obj.find('Decode');
64            if (await itr.hasNext())
65              new_img_obj.put('Decode', await itr.value());
66            itr = await obj.find('ImageMask');
67            if (await itr.hasNext())
68              new_img_obj.put('ImageMask', await itr.value());
69            itr = await obj.find('Mask');
70            if (await itr.hasNext())
71              new_img_obj.put('Mask', await itr.value());
72
73            await cos_doc.swap(i, await new_img_obj.getObjNum());
74          }
75        }
76
77        pdf_doc.save('../TestFiles/Output/US061222892_JBIG2.pdf', PDFNet.SDFDoc.SaveOptions.e_remove_unused);
78      } catch (err) {
79        console.log(err);
80      }
81    };
82    PDFNet.runWithCleanup(main, PDFTronLicense.Key).catch(function(error) {
83      console.log('Error: ' + JSON.stringify(error));
84    }).then(function(){ return PDFNet.shutdown(); });
85  };
86  exports.runJBIG2Test();
87})(exports);
88// eslint-disable-next-line spaced-comment
89//# sourceURL=JBIG2Test.js
1<?php
2//---------------------------------------------------------------------------------------
3// Copyright (c) 2001-2023 by Apryse Software Inc. All Rights Reserved.
4// Consult LICENSE.txt regarding license information.
5//---------------------------------------------------------------------------------------
6if(file_exists("../../../PDFNetC/Lib/PDFNetPHP.php"))
7include("../../../PDFNetC/Lib/PDFNetPHP.php");
8include("../../LicenseKey/PHP/LicenseKey.php");
9
10// Relative path to the folder containing the test files.
11$input_path = getcwd()."/../../TestFiles/";
12$output_path = $input_path."Output/";
13
14// This sample project illustrates how to recompress bi-tonal images in an 
15// existing PDF document using JBIG2 compression. The sample is not intended 
16// to be a generic PDF optimization tool.
17//
18// You can download the entire document using the following link:
19//   http://www.pdftron.com/net/samplecode/data/US061222892.pdf
20
21	PDFNet::Initialize($LicenseKey);
22	PDFNet::GetSystemFontList();    // Wait for fonts to be loaded if they haven't already. This is done because PHP can run into errors when shutting down if font loading is still in progress.
23
24	$pdf_doc = new PDFDoc("../../TestFiles/US061222892-a.pdf") ;
25	$pdf_doc->InitSecurityHandler();
26
27	$cos_doc = $pdf_doc->GetSDFDoc();
28	$num_objs = $cos_doc->XRefSize();
29	for($i = 1; $i < $num_objs; ++$i) 
30	{
31		$obj = $cos_doc->GetObj($i);
32		if($obj && !$obj->IsFree() && $obj->IsStream()) 
33		{
34			// Process only images
35			$itr = $obj->Find("Subtype");
36			if(!$itr->HasNext() || $itr->Value()->GetName() != "Image")
37				continue;
38			
39			$input_image = new Image($obj);
40			// Process only gray-scale images
41			if($input_image->GetComponentNum() != 1)
42				continue;
43			$bpc = $input_image->GetBitsPerComponent();
44			if($bpc != 1)	// Recompress only 1 BPC images
45				continue;
46
47			// Skip images that are already compressed using JBIG2
48			$itr = $obj->Find("Filter");
49			if ($itr->HasNext() && $itr->Value()->IsName() && 
50				$itr->Value()->GetName() == "JBIG2Decode") continue; 
51
52			$filter=$obj->GetDecodedStream();
53			$reader = new FilterReader($filter);
54
55
56			$hint_set = new ObjSet(); 	// A hint to image encoder to use JBIG2 compression
57			$hint=$hint_set->CreateArray();
58			
59			$hint->PushBackName("JBIG2");
60			$hint->PushBackName("Lossless");
61
62			$new_image = Image::Create($cos_doc, $reader, 
63				$input_image->GetImageWidth(), 
64				$input_image->GetImageHeight(), 1, ColorSpace::CreateDeviceGray(), $hint);
65
66			$new_img_obj = $new_image->GetSDFObj();
67			$itr = $obj->Find("Decode");
68			if($itr->HasNext())
69				$new_img_obj->Put("Decode", $itr->Value());
70			$itr = $obj->Find("ImageMask");
71			if ($itr->HasNext())
72				$new_img_obj->Put("ImageMask", $itr->Value());
73			$itr = $obj->Find("Mask");
74			if ($itr->HasNext())
75				$new_img_obj->Put("Mask", $itr->Value());
76
77			$cos_doc->Swap($i, $new_img_obj->GetObjNum());
78		}
79	}
80
81	$pdf_doc->Save("../../TestFiles/Output/US061222892_JBIG2.pdf", SDFDoc::e_remove_unused);
82	$pdf_doc->Close();
83	PDFNet::Terminate();
84	echo "Done.";
85?>
1#---------------------------------------------------------------------------------------
2# Copyright (c) 2001-2023 by Apryse Software Inc. All Rights Reserved.
3# Consult LICENSE.txt regarding license information.
4#---------------------------------------------------------------------------------------
5
6import site
7site.addsitedir("../../../PDFNetC/Lib")
8import sys
9from PDFNetPython import *
10
11sys.path.append("../../LicenseKey/PYTHON")
12from LicenseKey import *
13
14
15# This sample project illustrates how to recompress bi-tonal images in an 
16# existing PDF document using JBIG2 compression. The sample is not intended 
17# to be a generic PDF optimization tool.
18#
19# You can download the entire document using the following link:
20#   http://www.pdftron.com/net/samplecode/data/US061222892.pdf
21
22def main():
23    PDFNet.Initialize(LicenseKey)
24    
25    pdf_doc = PDFDoc("../../TestFiles/US061222892-a.pdf")
26    pdf_doc.InitSecurityHandler()
27    
28    cos_doc = pdf_doc.GetSDFDoc()
29    num_objs = cos_doc.XRefSize()
30    
31    i = 1
32    while i < num_objs:
33        obj = cos_doc.GetObj(i)
34        if obj is not None and not obj.IsFree() and obj.IsStream():
35            # Process only images
36            itr = obj.Find("Subtype")
37            if not itr.HasNext() or not itr.Value().GetName() == "Image":
38                i = i + 1
39                continue
40            
41            input_image = Image(obj)
42            # Process only gray-scale images
43            if input_image.GetComponentNum() != 1:
44                i = i + 1
45                continue
46            
47            # Skip images that are already compressed using JBIG2
48            itr = obj.Find("Filter")
49            if (itr.HasNext() and itr.Value().IsName() and itr.Value().GetName() == "JBIG2Decode"):
50                i = i + 1
51                continue
52            
53            filter = obj.GetDecodedStream()
54            reader = FilterReader(filter)
55            
56            hint_set = ObjSet()     # hint to image encoder to use JBIG2 compression
57            hint = hint_set.CreateArray()
58            
59            hint.PushBackName("JBIG2")
60            hint.PushBackName("Lossless")
61            
62            new_image = (Image.Create(cos_doc, reader, 
63                                     input_image.GetImageWidth(), 
64                                     input_image.GetImageHeight(), 
65                                     1, 
66                                     ColorSpace.CreateDeviceGray(), 
67                                     hint))
68            
69            new_img_obj = new_image.GetSDFObj()
70            itr = obj.Find("Decode")
71            
72            if itr.HasNext():
73                new_img_obj.Put("Decode", itr.Value())
74            itr = obj.Find("ImageMask")
75            if itr.HasNext():
76                new_img_obj.Put("ImageMask", itr.Value())
77            itr = obj.Find("Mask")
78            if itr.HasNext():
79                new_img_obj.Put("Mask", itr.Value())
80                
81            cos_doc.Swap(i, new_img_obj.GetObjNum())
82        i = i + 1
83            
84    pdf_doc.Save("../../TestFiles/Output/US061222892_JBIG2.pdf", SDFDoc.e_remove_unused)
85    pdf_doc.Close()                
86    PDFNet.Terminate()
87
88if __name__ == '__main__':
89    main()
1#---------------------------------------------------------------------------------------
2# Copyright (c) 2001-2023 by Apryse Software Inc. All Rights Reserved.
3# Consult LICENSE.txt regarding license information.
4#---------------------------------------------------------------------------------------
5
6require '../../../PDFNetC/Lib/PDFNetRuby'
7include PDFNetRuby
8require '../../LicenseKey/RUBY/LicenseKey'
9
10$stdout.sync = true
11
12# This sample project illustrates how to recompress bi-tonal images in an 
13# existing PDF document using JBIG2 compression. The sample is not intended 
14# to be a generic PDF optimization tool.
15#
16# You can download the entire document using the following link:
17#   http://www.pdftron.com/net/samplecode/data/US061222892.pdf
18
19	PDFNet.Initialize(PDFTronLicense.Key)
20	
21	pdf_doc = PDFDoc.new("../../TestFiles/US061222892-a.pdf")
22	pdf_doc.InitSecurityHandler
23	
24	cos_doc = pdf_doc.GetSDFDoc
25	num_objs = cos_doc.XRefSize
26	
27	i = 1
28	while i < num_objs do
29		obj = cos_doc.GetObj(i)
30		if !obj.nil? and !obj.IsFree and obj.IsStream
31			# Process only images
32			itr = obj.Find("Subtype")
33			if !itr.HasNext or !itr.Value.GetName == "Image"
34				i = i + 1
35				next
36			end
37			
38			input_image = Image.new(obj)
39			# Process only gray-scale images
40			if input_image.GetComponentNum != 1
41				i = i + 1
42				next
43			end			
44
45			# Skip images that are already compressed using JBIG2
46			itr = obj.Find("Filter")
47			if itr.HasNext and itr.Value.IsName and itr.Value.GetName == "JBIG2Decode"
48				i = i + 1
49				next
50			end
51			
52			filter = obj.GetDecodedStream
53			reader = FilterReader.new(filter)
54			
55			hint_set = ObjSet.new	 # hint to image encoder to use JBIG2 compression
56			hint = hint_set.CreateArray
57			
58			hint.PushBackName("JBIG2")
59			hint.PushBackName("Lossless")
60			
61			new_image = Image.Create(cos_doc, reader, 
62						input_image.GetImageWidth, 
63						input_image.GetImageHeight, 
64						1, 
65						ColorSpace.CreateDeviceGray, 
66						hint)
67			
68			new_img_obj = new_image.GetSDFObj
69			itr = obj.Find("Decode")
70			
71			if itr.HasNext
72				new_img_obj.Put("Decode", itr.Value)
73			end
74			itr = obj.Find("ImageMask")
75			if itr.HasNext
76				new_img_obj.Put("ImageMask", itr.Value)
77			end
78			itr = obj.Find("Mask")
79			if itr.HasNext
80				new_img_obj.Put("Mask", itr.Value)
81			end
82				
83			cos_doc.Swap(i, new_img_obj.GetObjNum)
84		end
85		i = i + 1
86	end
87			
88	pdf_doc.Save("../../TestFiles/Output/US061222892_JBIG2.pdf", SDFDoc::E_remove_unused)
89	pdf_doc.Close
90	PDFNet.Terminate
1'
2' Copyright (c) 2001-2024 by Apryse Software Inc. All Rights Reserved.
3'
4Imports System.Windows.Forms
5
6Imports pdftron
7Imports pdftron.Common
8Imports pdftron.Filters
9Imports pdftron.SDF
10Imports pdftron.PDF
11
12' This sample project illustrates how to recompress bi-tonal images in an 
13' existing PDF document using JBIG2 compression. The sample is not intended 
14' to be a generic PDF optimization tool.
15' 
16' You can download a sample scanned document using the following link:
17'   http://www.pdftron.com/net/samplecode/data/US061222892.pdf
18'
19' Also a sample page compressed using CCITT Fax compression is located under 
20' 'PDFNet/Samples/TestFiles' folder.
21
22Module Program
23    Dim pdfNetLoader As PDFNetLoader
24    Sub New()
25        pdfNetLoader = pdftron.PDFNetLoader.Instance()
26    End Sub
27
28    Sub Main(args As String())
29        ' Initialize PDFNet before calling any other PDFNet function.
30        PDFNet.Initialize(PDFTronLicense.Key)
31
32        Dim pdfdoc As PDFDoc = New PDFDoc("../../../../TestFiles/US061222892-a.pdf")
33        pdfdoc.InitSecurityHandler()
34        Dim cos_doc As SDFDoc = pdfdoc.GetSDFDoc()
35        Dim num_objs As Integer = cos_doc.XRefSize()
36
37        For i As Integer = 1 To num_objs - 1
38            Dim obj As Obj = cos_doc.GetObj(i)
39            If Not (obj Is Nothing Or obj.IsFree()) Then
40                ' Process only images
41                If obj.IsStream() Then
42                    Dim itr As DictIterator = obj.Find("Subtype")
43                    If itr.HasNext() Then
44                        If itr.Value().GetName() = "Image" Then
45                            Dim input_image As pdftron.PDF.Image = New pdftron.PDF.Image(obj)
46                            Dim new_image As pdftron.PDF.Image = Nothing
47
48                            ' Process only gray-scale images
49                            If input_image.GetComponentNum() = 1 Then
50                                Dim bpc As Integer = input_image.GetBitsPerComponent()
51                                If bpc = 1 Then
52                                    Dim reader As FilterReader = New FilterReader(obj.GetDecodedStream())
53
54                                    Dim hint_set As ObjSet = New ObjSet
55                                    Dim hint As Obj = hint_set.CreateArray()
56                                    hint.PushBackName("JBIG2")
57                                    ' hint.PushBackName("Lossless")
58                                    hint.PushBackName("Threshold")
59                                    hint.PushBackNumber(0.4)
60                                    hint.PushBackName("SharePages")
61                                    hint.PushBackNumber(10000)
62
63                                    new_image = pdftron.PDF.Image.Create(cos_doc, reader, input_image.GetImageWidth(), input_image.GetImageHeight(), 1, ColorSpace.CreateDeviceGray(), hint)
64                                End If
65
66                                If Not new_image Is Nothing Then
67                                    Dim new_img_obj As Obj = new_image.GetSDFObj()
68
69                                    ' Copy any important entries from the image dictionary
70                                    itr = obj.Find("ImageMask")
71                                    If itr.HasNext() Then
72                                        new_img_obj.Put("ImageMask", itr.Value())
73                                    End If
74                                    itr = obj.Find("Mask")
75                                    If itr.HasNext() Then
76                                        new_img_obj.Put("Mask", itr.Value())
77                                    End If
78                                    cos_doc.Swap(i, new_image.GetSDFObj().GetObjNum())
79                                End If
80                            End If
81                        End If
82                    End If
83                End If
84            End If
85        Next
86
87        pdfdoc.Save("../../../../TestFiles/Output/US061222892_JBIG2.pdf", SDFDoc.SaveOptions.e_remove_unused)
88        pdfdoc.Close()
89        PDFNet.Terminate()
90    End Sub
91End Module
Did you find this helpful?
Trial setup questions?
Ask experts on DiscordNeed other help?
Contact SupportPricing or product questions?
Contact Sales