> 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/core/get-started/samples/imageextracttest.md).

# Extract Image from PDFs - ImageExtract

Here is a sample showcasing how to extract image from pdf with Apryse SDK - free trial.  Samples provided in Python, C++, C#, Java, Node.js (JavaScript), PHP, Ruby and VB.

Sample code for using Apryse SDK to extract images from PDF files, along with their positioning information and DPI; provided in Python, C++, C#, Java, Node.js (JavaScript), PHP, Ruby and VB. Instead of converting PDF images to a Bitmap, you can also extract uncompressed/compressed image data directly using element.GetImageData() (described in the [PDF Data Extraction](/core/get-started/samples/imageextracttest.md) code sample).

Learn more about our full [PDF Data Extraction SDK Capabilities](https://apryse.com/capabilities/extraction).

To start your free trial, [get stated with Server SDK](/core/get-started/get-started.md).

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

```csharp
//
// Copyright (c) 2001-2024 by Apryse Software Inc. All Rights Reserved.
//

using System;
using System.Drawing;
using System.Drawing.Imaging;

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

namespace ImageExtractTestCS
{
	class Class1
	{
		/// <summary>
		///-----------------------------------------------------------------------------------
		/// This sample illustrates one approach to PDF image extraction 
		/// using PDFNet.
		/// 
		/// Note: Besides direct image export, you can also convert PDF images 
		/// to GDI+ Bitmap, or extract uncompressed/compressed image data directly 
		/// using element.GetImageData() (e.g. as illustrated in ElementReaderAdv 
		/// sample project).
		///-----------------------------------------------------------------------------------
		/// </summary>

		private static pdftron.PDFNetLoader pdfNetLoader = pdftron.PDFNetLoader.Instance();
		static Class1() {}

		static int image_counter = 0;

		// Relative path to the folder containing test files.
		static string input_path =  "../../../../TestFiles/";
		static string output_path = "../../../../TestFiles/Output/";

		static void ImageExtract(PDFDoc doc, ElementReader reader) 
		{
			Element element; 
			while ((element = reader.Next()) != null)
			{
				switch (element.GetType()) 
				{
					case Element.Type.e_image:
					case Element.Type.e_inline_image:
					{
						Console.WriteLine("--> Image: {0}", ++image_counter);
						Console.WriteLine("    Width: {0}", element.GetImageWidth());
						Console.WriteLine("    Height: {0}", element.GetImageHeight());
						Console.WriteLine("    BPC: {0}", element.GetBitsPerComponent());

						Matrix2D ctm = element.GetCTM();
						double x2=1, y2=1, y1=ctm.m_v;
						ctm.Mult(ref x2, ref y2);
						// Write the coords to 3 decimal places.
						Console.WriteLine("    Coords: x1={0:N2}, y1={1:N2}, x2={2:N2}, y2={3:N2}", ctm.m_h, ctm.m_v, x2, y2);
						pdftron.PDF.Image image = null;
						if (element.GetType() == Element.Type.e_image) 
						{
							image = new pdftron.PDF.Image(element.GetXObject());

							string fname = output_path + "image_extract1_" + image_counter.ToString();
							image.Export(fname);  // or ExporAsPng() or ExporAsTiff() ...
						}
						break;
					}
					case Element.Type.e_form: // Process form XObjects
					{
						reader.FormBegin(); 
						ImageExtract(doc, reader);
						reader.End(); 
						break; 
					}
				}
			}
		}

		static void Main(string[] args)
		{
			PDFNet.Initialize(PDFTronLicense.Key);
			
			// Example 1: 
			// Extract images by traversing the display list for 
			// every page. With this approach it is possible to obtain 
			// image positioning information and DPI.
			try	
			{
				using (PDFDoc doc = new PDFDoc(input_path + "newsletter.pdf"))
				using (ElementReader reader = new ElementReader())
				{
					doc.InitSecurityHandler();
					PageIterator itr;
					for (itr=doc.GetPageIterator(); itr.HasNext(); itr.Next())	
					{				
						reader.Begin(itr.Current());
						ImageExtract(doc, reader);
						reader.End();
					}

					Console.WriteLine("Done.");
				}
			}
			catch (PDFNetException e)
			{
				Console.WriteLine(e.Message);
			}

			Console.WriteLine("----------------------------------------------------------------");

			// Example 2: 
			// Extract images by scanning the low-level document.
			try	
			{
				using (PDFDoc doc = new PDFDoc(input_path + "newsletter.pdf"))
				{
					doc.InitSecurityHandler();
					image_counter = 0;

					SDFDoc cos_doc = 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; 

							itr = obj.Find("Type");
							if (!itr.HasNext() || itr.Value().GetName() != "XObject") 
								continue;

							pdftron.PDF.Image image = new pdftron.PDF.Image(obj);

							Console.WriteLine("--> Image: {0}", ++image_counter);
							Console.WriteLine("    Width: {0}", image.GetImageWidth());
							Console.WriteLine("    Height: {0}", image.GetImageHeight());
							Console.WriteLine("    BPC: {0}", image.GetBitsPerComponent());

							string fname = output_path + "image_extract2_" + image_counter.ToString();
							image.Export(fname);  // or ExporAsPng() or ExporAsTiff() ...

							// Convert PDF bitmap to GDI+ Bitmap...
							//Bitmap bmp = image.GetBitmap();
							//bmp.Save(fname, ImageFormat.Png);
							//bmp.Dispose();

							// Instead of converting PDF images to a Bitmap, you can also extract 
							// uncompressed/compressed image data directly using element.GetImageData() 
							// as illustrated in ElementReaderAdv sample project.
						}
					}
					Console.WriteLine("Done.");
				}
			}
			catch (PDFNetException e)
			{
				Console.WriteLine(e.Message);
			}
			PDFNet.Terminate();

		}
	}
}
```

{% endcode %}
{% endtab %}

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

```go
//---------------------------------------------------------------------------------------
// Copyright (c) 2001-2021 by PDFTron Systems Inc. All Rights Reserved.
// Consult LICENSE.txt regarding license information.
//---------------------------------------------------------------------------------------

package main
import (
    "fmt"
    "strconv"
    . "pdftron"
)

import  "pdftron/Samples/LicenseKey/GO"

//-----------------------------------------------------------------------------------
// This sample illustrates one approach to PDF image extraction 
// using PDFNet.
// 
// Note: Besides direct image export, you can also convert PDF images 
// to GDI+ Bitmap, or extract uncompressed/compressed image data directly 
// using element.GetImageData() (e.g. as illustrated in ElementReaderAdv 
// sample project).
//-----------------------------------------------------------------------------------

var imageCounter = 0

// Relative path to the folder containing the test files.
var inputPath = "../../TestFiles/"
var outputPath = "../../TestFiles/Output/"

func ImageExtract(reader ElementReader){
    element := reader.Next()

    for element.GetMp_elem().Swigcptr() != 0{
        if (element.GetType() == ElementE_image ||
            element.GetType() == ElementE_inline_image){
            imageCounter += 1
            fmt.Println("--> Image: " + strconv.Itoa(imageCounter))
            fmt.Println("    Width: " + strconv.Itoa(element.GetImageWidth()))
            fmt.Println("    Height: " + strconv.Itoa(element.GetImageHeight()))
            fmt.Println("    BPC: " + strconv.Itoa(element.GetBitsPerComponent()))
            
            ctm := element.GetCTM()
            x2 := 1
            y2 := 1
            pt := NewPoint(float64(x2), float64(y2))
            point := ctm.Mult(pt)
            fmt.Println("    Coords: x1=%.2f, y1=%.2f, x2=%.2f, y2=%.2f", ctm.GetM_h(), ctm.GetM_v(), point.GetX(), point.GetY())
            
            if element.GetType() == ElementE_image{
                image := NewImage(element.GetXObject())
                
                fname := "image_extract1_" + strconv.Itoa(imageCounter)
                
                path := outputPath + fname
                image.Export(path)
                
                //path = outputPath + fname + ".tif"
                //image.ExportAsTiff(path)
                
                //path = outputPath + fname + ".png"
                //image.ExportAsPng(path)
            }
        }else if element.GetType() == ElementE_form{
            reader.FormBegin()
            ImageExtract(reader)
            reader.End() 
        }
        element = reader.Next()
    }
}

func main(){
    // Initialize PDFNet
    PDFNetInitialize(PDFTronLicense.Key)    
    
    // Example 1: 
    // Extract images by traversing the display list for 
    // every page. With this approach it is possible to obtain 
    // image positioning information and DPI.
    
    doc := NewPDFDoc(inputPath + "newsletter.pdf")
    doc.InitSecurityHandler()
    
    reader := NewElementReader()
    
    // Read every page
    itr := doc.GetPageIterator()
    for itr.HasNext(){
        reader.Begin(itr.Current())
        ImageExtract(reader)
        reader.End()
        itr.Next()
    }

    doc.Close()
    fmt.Println("Done.")
    
    fmt.Println("----------------------------------------------------------------")
    
    // Example 2: 
    // Extract images by scanning the low-level document.
    
    doc = NewPDFDoc(inputPath + "newsletter.pdf")
    doc.InitSecurityHandler()
    imageCounter= 0
    
    cosDoc := doc.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("Type")
            
            if (!itr.HasNext()) || (itr.Value().GetName() != "XObject"){
                i = i + 1
                continue
            }
            itr = obj.Find("Subtype")
            if (!itr.HasNext()) || (itr.Value().GetName() != "Image"){
                i = i + 1
                continue
            }
            image := NewImage(obj)
            
            imageCounter = imageCounter + 1
            fmt.Println("--> Image: " + strconv.Itoa(imageCounter))
            fmt.Println("    Width: " + strconv.Itoa(image.GetImageWidth()))
            fmt.Println("    Height: " + strconv.Itoa(image.GetImageHeight()))
            fmt.Println("    BPC: " + strconv.Itoa(image.GetBitsPerComponent()))
            
            fname := "image_extract2_" + strconv.Itoa(imageCounter)
                
            path := outputPath + fname
            image.Export(path)
            
            //path = outputPath + fname + ".tif"
            //image.ExportAsTiff(path)
            
            //path = outputPath + fname + ".png"
            //image.ExportAsPng(path)
        }
        i = i + 1
    }
    doc.Close()
    PDFNetTerminate()
    fmt.Println("Done.")
}
```

{% endcode %}
{% endtab %}

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

```java
//---------------------------------------------------------------------------------------
// Copyright (c) 2001-2024 by Apryse Software Inc. All Rights Reserved.
// Consult legal.txt regarding legal and license information.
//---------------------------------------------------------------------------------------

import com.pdftron.common.Matrix2D;
import com.pdftron.common.PDFNetException;
import com.pdftron.pdf.*;
import com.pdftron.sdf.DictIterator;
import com.pdftron.sdf.Obj;
import com.pdftron.sdf.SDFDoc;

///-----------------------------------------------------------------------------------
/// This sample illustrates one approach to PDF image extraction 
/// using PDFNet.
/// 
/// Note: Besides direct image export, you can also convert PDF images 
/// to Java image, or extract uncompressed/compressed image data directly 
/// using element.GetImageData() (e.g. as illustrated in ElementReaderAdv 
/// sample project).
///-----------------------------------------------------------------------------------
public class ImageExtractTest {

    // Relative paths to folders containing test files.
    static String input_path = "../../TestFiles/";
    static String output_path = "../../TestFiles/Output/";

    static int image_counter = 0;

    static void ImageExtract(ElementReader reader) throws PDFNetException {
        Element element;
        while ((element = reader.next()) != null) {
            switch (element.getType()) {
                case Element.e_image:
                case Element.e_inline_image: {
                    System.out.println("--> Image: " + (++image_counter));
                    System.out.println("    Width: " + element.getImageWidth());
                    System.out.println("    Height: " + element.getImageHeight());
                    System.out.println("    BPC: " + element.getBitsPerComponent());

                    Matrix2D ctm = element.getCTM();
                    double x2 = 1, y2 = 1;
                    java.awt.geom.Point2D.Double p = ctm.multPoint(x2, y2);
                    System.out.println(String.format("    Coords: x1=%.2f, y1=%.2f, x2=%.2f, y2=%.2f", ctm.getH(), ctm.getV(), p.getX(), p.getY()));

                    if (element.getType() == Element.e_image) {
                        Image image = new Image(element.getXObject());

                        String fname = "image_extract1_" + image_counter;

                        String path = output_path + fname;
                        image.export(path);

                        //String path2 = output_path + fname + ".tif";
                        //image.exportAsTiff(path2);

                        //String path3 = output_path + fname + ".png";
                        //image.exportAsPng(path3);
                    }
                }
                break;
                case Element.e_form:        // Process form XObjects
                    reader.formBegin();
                    ImageExtract(reader);
                    reader.end();
                    break;
            }
        }
    }

    public static void main(String[] args) {
        // Initialize PDFNet
        PDFNet.initialize(PDFTronLicense.Key());

        // Example 1:
        // Extract images by traversing the display list for
        // every page. With this approach it is possible to obtain
        // image positioning information and DPI.
        try (PDFDoc doc = new PDFDoc((input_path + "newsletter.pdf"))) {
            doc.initSecurityHandler();
            ElementReader reader = new ElementReader();
            //  Read every page
            for (PageIterator itr = doc.getPageIterator(); itr.hasNext(); ) {
                reader.begin(itr.next());
                ImageExtract(reader);
                reader.end();
            }
            System.out.println("Done.");
        } catch (Exception e) {
            e.printStackTrace();
        }


        System.out.println("----------------------------------------------------------------");

        // Example 2:
        // Extract images by scanning the low-level document.
        try (PDFDoc doc = new PDFDoc((input_path + "newsletter.pdf"))) {
            doc.initSecurityHandler();
            image_counter = 0;
            SDFDoc cos_doc = doc.getSDFDoc();
            long 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("Type");
                    if (!itr.hasNext() || !itr.value().getName().equals("XObject"))
                        continue;

                    itr = obj.find("Subtype");
                    if (!itr.hasNext() || !itr.value().getName().equals("Image"))
                        continue;

                    Image image = new Image(obj);

                    System.out.println("--> Image: " + (++image_counter));
                    System.out.println("    Width: " + image.getImageWidth());
                    System.out.println("    Height: " + image.getImageHeight());
                    System.out.println("    BPC: " + image.getBitsPerComponent());

                    String fname = "image_extract2_" + image_counter;
                    String path = output_path + fname;
                    image.export(path);

                    //String path= output_path + fname + ".tif";
                    //image.exportAsTiff(path);

                    //String path = output_path + fname + ".png";
                    //image.exportAsPng(path);
                }
            }
            
            System.out.println("Done.");
        } catch (Exception e) {
            e.printStackTrace();
        }

        PDFNet.terminate();
    }
}
```

{% endcode %}
{% endtab %}

{% tab title="C++" %}
{% code lineNumbers="true" %}

```cpp
//---------------------------------------------------------------------------------------
// Copyright (c) 2001-2024 by Apryse Software Inc. All Rights Reserved.
// Consult legal.txt regarding legal and license information.
//---------------------------------------------------------------------------------------

#include <PDF/PDFNet.h>
#include <PDF/PDFDoc.h>
#include <PDF/ElementReader.h>
#include <PDF/Image.h>
#include "../../LicenseKey/CPP/LicenseKey.h"

//-----------------------------------------------------------------------------------
// This sample illustrates one approach to PDF image extraction 
// using PDFNet.
// 
// Note: Besides direct image export, you can also convert PDF images 
// to GDI+ Bitmap, or extract uncompressed/compressed image data directly 
// using element.GetImageData() (e.g. as illustrated in ElementReaderAdv 
// sample project).
//-----------------------------------------------------------------------------------

#include <iostream>
#include <iomanip>

using namespace std;

using namespace pdftron;
using namespace Common;
using namespace SDF;
using namespace PDF;

// Relative paths to folders containing test files.
string input_path =  "../../TestFiles/";
string output_path = "../../TestFiles/Output/";

int image_counter = 0;

void ImageExtract(ElementReader& reader) 
{
	// Set the precision for printing doubles on cout to 3 decimal places.
	ios iostate(NULL);
	iostate.copyfmt(cout);
	cout << fixed << showpoint << setprecision(3);

	Element element; 
	while ((element = reader.Next()) != 0)
	{
		switch (element.GetType()) 
		{
		case Element::e_image: 
		case Element::e_inline_image: 
			{
				cout << "--> Image: " << ++image_counter << endl;
				cout << "    Width: " << element.GetImageWidth() << endl;
				cout << "    Height: " << element.GetImageHeight() << endl;
				cout << "    BPC: " << element.GetBitsPerComponent() << endl;

				Common::Matrix2D ctm = element.GetCTM();
				double x2=1, y2=1;
				ctm.Mult(x2, y2);
				printf("    Coords: x1=%.2f, y1=%.2f, x2=%.2f, y2=%.2f\n", ctm.m_h, ctm.m_v, x2, y2);

				if (element.GetType() == Element::e_image) 
				{
					Image image(element.GetXObject());

					char fname[256];
					sprintf(fname, "image_extract1_%d", image_counter);

					string path(output_path + fname);
					image.Export(path.c_str());

					//string path(output_path + fname + ".tif");
					//image.ExportAsTiff(path.c_str());

					//string path(output_path + fname + ".png");
					//image.ExportAsPng(path.c_str());
				}
			}
			break;
		case Element::e_form:		// Process form XObjects
			reader.FormBegin(); 
			ImageExtract(reader);
			reader.End(); 
			break; 
		}
	}

	// Reset cout's state.
	cout.copyfmt(iostate);
}

int main(int argc, char *argv[])
{
	int ret = 0;

	// Initialize PDFNet
	PDFNet::Initialize(LicenseKey);

	// Example 1: 
	// Extract images by traversing the display list for 
	// every page. With this approach it is possible to obtain 
	// image positioning information and DPI.
	try  
	{	 
		PDFDoc doc((input_path + "newsletter.pdf").c_str());
		doc.InitSecurityHandler();
		ElementReader reader;
		//  Read every page
		for (PageIterator itr=doc.GetPageIterator(); itr.HasNext(); itr.Next()) 
		{				
			reader.Begin(itr.Current());
			ImageExtract(reader);
			reader.End();
		}

		cout << "Done." << endl;
	}
	catch(Common::Exception& e)
	{
		cout << e << endl;
		ret = 1;
	}
	catch(...)
	{
		cout << "Unknown Exception" << endl;
		ret = 1;
	}

	cout << "----------------------------------------------------------------" << endl;

	// Example 2: 
	// Extract images by scanning the low-level document.
	try  
	{	 
		PDFDoc doc((input_path + "newsletter.pdf").c_str());

		doc.InitSecurityHandler();
		image_counter = 0;

		SDFDoc& cos_doc=doc.GetSDFDoc();
		int num_objs = cos_doc.XRefSize();
		for(int i=1; i<num_objs; ++i) 
		{
			Obj obj = cos_doc.GetObj(i);
			if(obj && !obj.IsFree() && obj.IsStream()) 
			{
				// Process only images
				DictIterator itr = obj.Find("Type");
				if(!itr.HasNext() || strcmp(itr.Value().GetName(), "XObject"))
					continue;

				itr = obj.Find("Subtype");
				if(!itr.HasNext() || strcmp(itr.Value().GetName(), "Image"))
					continue;
				
				PDF::Image image(obj);
				cout << "--> Image: " << ++image_counter << endl;
				cout << "    Width: " << image.GetImageWidth() << endl;
				cout << "    Height: " << image.GetImageHeight() << endl;
				cout << "    BPC: " << image.GetBitsPerComponent() << endl;

				char fname[256];
				sprintf(fname, "image_extract2_%d", image_counter);
				string path(output_path + fname);
				image.Export(path.c_str());

				//string path(output_path + fname + ".tif");
				//image.ExportAsTiff(path.c_str());

				//string path(output_path + fname + ".png");
				//image.ExportAsPng(path.c_str());
			}
		}

		cout << "Done." << endl;
	}
	catch(Common::Exception& e)
	{
		cout << e << endl;
		ret = 1;
	}
	catch(...)
	{
		cout << "Unknown Exception" << endl;
		ret = 1;
	}

	PDFNet::Terminate();
	return ret;
}
```

{% endcode %}
{% endtab %}

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

```php
<?php
//---------------------------------------------------------------------------------------
// Copyright (c) 2001-2023 by Apryse Software Inc. All Rights Reserved.
// Consult LICENSE.txt regarding license information.
//---------------------------------------------------------------------------------------
if(file_exists("../../../PDFNetC/Lib/PDFNetPHP.php"))
include("../../../PDFNetC/Lib/PDFNetPHP.php");
include("../../LicenseKey/PHP/LicenseKey.php");

// Relative path to the folder containing the test files.
$input_path = getcwd()."/../../TestFiles/";
$output_path = $input_path."Output/";

//-----------------------------------------------------------------------------------
// This sample illustrates one approach to PDF image extraction 
// using PDFNet.
// 
// Note: Besides direct image export, you can also convert PDF images 
// to GDI+ Bitmap, or extract uncompressed/compressed image data directly 
// using element.GetImageData() (e.g. as illustrated in ElementReaderAdv 
// sample project).
//-----------------------------------------------------------------------------------

$image_counter = 0;

function ImageExtract($reader) 
{
	while (($element = $reader->Next()) != null)
	{
		switch ($element->GetType()) 
		{
		case Element::e_image: 
		case Element::e_inline_image: 
			{
				global $image_counter;
				echo nl2br("--> Image: ".++$image_counter."\n");
				echo nl2br("    Width: ".$element->GetImageWidth()."\n");
				echo nl2br("    Height: ".$element->GetImageHeight()."\n");
				echo nl2br("    BPC: ".$element->GetBitsPerComponent()."\n");

				$ctm = $element->GetCTM();
				$x2=1.0;
				$y2=1.0;
				$point = $ctm->Mult(new Point($x2, $y2));
				printf("    Coords: x1=%.2f, y1=%.2f, x2=%.2f, y2=%.2f\n", $ctm->m_h, $ctm->m_v, $point->x, $point->y);
				if ($element->GetType() == Element::e_image) 
				{
					$image = new Image($element->GetXObject());

					$fname = "image_extract1_".$image_counter;
					global $output_path;
					$path = $output_path.$fname;
					$image->Export($path);

					//$path = $output_path.$fname.".tif";
					//$image->ExportAsTiff($path);

					//$path = $output_path $fname.".png";
					//$image->ExportAsPng($path);
				}
			}
			break;
		case Element::e_form:		// Process form XObjects
			$reader->FormBegin(); 
			ImageExtract($reader);
			$reader->End(); 
			break; 
		}
	}
}

	// Initialize PDFNet
	PDFNet::Initialize($LicenseKey);
	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.

	// Example 1: 
	// Extract images by traversing the display list for 
	// every page. With this approach it is possible to obtain 
	// image positioning information and DPI.
	$doc = new PDFDoc($input_path."newsletter.pdf");
	$doc->InitSecurityHandler();

	$reader = new ElementReader();
	//  Read every page
	for ($itr=$doc->GetPageIterator(); $itr->HasNext(); $itr->Next()) 
	{				
		$reader->Begin($itr->Current());
		ImageExtract($reader);
		$reader->End();
	}

	$doc->Close();
	echo nl2br("Done.\n");

	echo nl2br("----------------------------------------------------------------\n");

	// Example 2: 
	// Extract images by scanning the low-level document.
	$doc = new PDFDoc($input_path."newsletter.pdf");

	$doc->InitSecurityHandler();
	$image_counter = 0;

	$cos_doc=$doc->GetSDFDoc();
	$num_objs = $cos_doc->XRefSize();
	for($i=1; $i<$num_objs; ++$i) 
	{
		$obj = $cos_doc->GetObj($i);
		if($obj != null && !$obj->IsFree() && $obj->IsStream()) 
		{
			// Process only images
			$itr = $obj->Find("Type");
			if(!$itr->HasNext() || !($itr->Value()->GetName() == "XObject"))
			{
				continue;
			}

			$itr = $obj->Find("Subtype");
			if(!$itr->HasNext() || !($itr->Value()->GetName() == "Image"))
			{
				continue;
			}
				
			$image = new Image($obj);
			echo nl2br("--> Image: ".++$image_counter."\n");
			echo nl2br("    Width: ".$image->GetImageWidth()."\n");
			echo nl2br("    Height: ".$image->GetImageHeight()."\n");
			echo nl2br("    BPC: ".$image->GetBitsPerComponent()."\n");

			$fname = "image_extract2_".$image_counter;
			$path = $output_path.$fname;
			$image->Export($path);

			//$path = $output_path.$fname.".tif");
			//$image->ExportAsTiff($path);

			//$path = $output_path.fname.".png");
			//$image->ExportAsPng($path);
		}
	}

	$doc->Close();
	PDFNet::Terminate();
	echo nl2br("Done.\n");
	
?>
```

{% endcode %}
{% endtab %}

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

```js
//---------------------------------------------------------------------------------------
// Copyright (c) 2001-2024 by Apryse Software Inc. All Rights Reserved.
// Consult legal.txt regarding legal and license information.
//---------------------------------------------------------------------------------------

//-----------------------------------------------------------------------------------
// This sample illustrates one approach to PDF image extraction 
// using PDFNet.
// 
// Note: Besides direct image export, you can also convert PDF images 
// to GDI+ Bitmap, or extract uncompressed/compressed image data directly 
// using element.GetImageData() (e.g. as illustrated in ElementReaderAdv 
// sample project).
//-----------------------------------------------------------------------------------

const { PDFNet } = require('@pdftron/pdfnet-node');
const PDFTronLicense = require('../LicenseKey/LicenseKey');

((exports) => {
  'use strict';

  exports.runImageExtractTest = () => {

    let image_counter = 0;
    const outputPath = '../TestFiles/Output/';

    const imageExtract = async (reader) => {
      let element;
      while ((element = await reader.next()) !== null) {
        switch (await element.getType()) {
          case PDFNet.Element.Type.e_image:
          case PDFNet.Element.Type.e_inline_image:
            console.log('--> Image: ' + ++image_counter);
            console.log('    Width: ' + await element.getImageWidth());
            console.log('    Height: ' + await element.getImageHeight());
            console.log('    BPC: ' + await element.getBitsPerComponent());

            const ctm = await element.getCTM();
            let x2 = 1, y2 = 1;
            const result = await ctm.mult(x2, y2);
            x2 = result.x;
            y2 = result.y;
            console.log('    Coords: x1=' + ctm.m_h.toFixed(2) + ', y1=' + ctm.m_v.toFixed(2)
             + ', x2=' + x2.toFixed(2) + ', y2=' + y2.toFixed(2));

            if (await element.getType() == PDFNet.Element.Type.e_image) {
              const image = await PDFNet.Image.createFromObj(await element.getXObject());
              image.export(outputPath + 'image_extract1_' + image_counter);
            }
            break;
          case PDFNet.Element.Type.e_form: // Process form XObjects
            reader.formBegin();
            await imageExtract(reader);
            reader.end();
            break;
        }
      }
    }

    const main = async () => {

      // Example 1: 
      // Extract images by traversing the display list for 
      // every page. With this approach it is possible to obtain 
      // image positioning information and DPI.
      try {
        const doc = await PDFNet.PDFDoc.createFromFilePath('../TestFiles/newsletter.pdf');
        doc.initSecurityHandler();

        const reader = await PDFNet.ElementReader.create();
        const itr = await doc.getPageIterator(1);
        // Read every page
        for (itr; await itr.hasNext(); await itr.next()) {
          const page = await itr.current();
          reader.beginOnPage(page);
          await imageExtract(reader);
          reader.end();
        }

        console.log('Done.');
      } catch (err) {
        console.log(err);
      }

      console.log('----------------------------------------------------------------');

      // Example 2: 
      // Extract images by scanning the low-level document.
      try {
        const doc = await PDFNet.PDFDoc.createFromFilePath('../TestFiles/newsletter.pdf');
        doc.initSecurityHandler();
        image_counter = 0;

        const cos_doc = await doc.getSDFDoc();
        const num_objs = await cos_doc.xRefSize();
        for (var i = 0; i < num_objs; i++) {
          const obj = await cos_doc.getObj(i);
          if (obj && !(await obj.isFree()) && await obj.isStream()) {
            // Process only images
            var itr = await obj.find('Type');
            if (!(await itr.hasNext()) || await (await itr.value()).getName() !== 'XObject')
              continue;

            itr = await obj.find('Subtype');
            if (!(await itr.hasNext()) || await (await itr.value()).getName() !== 'Image')
              continue;
            const image = await PDFNet.Image.createFromObj(obj);
            console.log('--> Image: ' + ++image_counter);
            console.log('    Width: ' + await image.getImageWidth());
            console.log('    Height: ' + await image.getImageHeight());
            console.log('    BPC: ' + await image.getBitsPerComponent());

            image.export(outputPath + 'image_extract2_' + image_counter);
          }
        }

        console.log('Done.');
      } catch (err) {
        console.log(err);
      }

    }
    PDFNet.runWithCleanup(main, PDFTronLicense.Key).catch(function(error) {
      console.log('Error: ' + JSON.stringify(error));
    }).then(function(){ return PDFNet.shutdown(); });
  };
  exports.runImageExtractTest();
})(exports);
// eslint-disable-next-line spaced-comment
//# sourceURL=ImageExtractTest.js
```

{% endcode %}
{% endtab %}

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

```python
#---------------------------------------------------------------------------------------
# Copyright (c) 2001-2023 by Apryse Software Inc. All Rights Reserved.
# Consult LICENSE.txt regarding license information.
#---------------------------------------------------------------------------------------

import site
site.addsitedir("../../../PDFNetC/Lib")
import sys
from PDFNetPython import *

sys.path.append("../../LicenseKey/PYTHON")
from LicenseKey import *

#-----------------------------------------------------------------------------------
# This sample illustrates one approach to PDF image extraction 
# using PDFNet.
# 
# Note: Besides direct image export, you can also convert PDF images 
# to GDI+ Bitmap, or extract uncompressed/compressed image data directly 
# using element.GetImageData() (e.g. as illustrated in ElementReaderAdv 
# sample project).
#-----------------------------------------------------------------------------------

image_counter = 0

# Relative path to the folder containing the test files.
input_path = "../../TestFiles/"
output_path = "../../TestFiles/Output/"

def ImageExtract(reader):
    element = reader.Next()
    while element != None:
        if (element.GetType() == Element.e_image or
            element.GetType() == Element.e_inline_image):
            global image_counter
            image_counter =image_counter + 1
            print("--> Image: " + str(image_counter))
            print("    Width: " + str(element.GetImageWidth()))
            print("    Height: " + str(element.GetImageHeight()))
            print("    BPC: " + str(element.GetBitsPerComponent()))
            
            ctm = element.GetCTM()
            x2 = 1
            y2 = 1
            pt = Point(x2, y2)
            point = ctm.Mult(pt)
            print("    Coords: x1=%.2f, y1=%.2f, x2=%.2f, y2=%.2f" % (ctm.m_h, ctm.m_v, point.x, point.y))
            
            if element.GetType() == Element.e_image:
                image = Image(element.GetXObject())
                
                fname = "image_extract1_" + str(image_counter)
                
                path = output_path + fname
                image.Export(path)
                
                #path = output_path + fname + ".tif"
                #image.ExportAsTiff(path)
                
                #path = output_path + fname + ".png"
                #image.ExportAsPng(path)
        elif element.GetType() == Element.e_form:
            reader.FormBegin()
            ImageExtract(reader)
            reader.End()            
        element = reader.Next()

def main():
    # Initialize PDFNet
    PDFNet.Initialize(LicenseKey)    
    
    # Example 1: 
    # Extract images by traversing the display list for 
    # every page. With this approach it is possible to obtain 
    # image positioning information and DPI.
    
    doc = PDFDoc(input_path + "newsletter.pdf")
    doc.InitSecurityHandler()
    
    reader = ElementReader()
    
    # Read every page
    itr = doc.GetPageIterator()
    while itr.HasNext():
        reader.Begin(itr.Current())
        ImageExtract(reader)
        reader.End()
        itr.Next()

    doc.Close()
    print("Done.")
    
    print("----------------------------------------------------------------")
    
    # Example 2: 
    # Extract images by scanning the low-level document.
    
    doc = PDFDoc(input_path + "newsletter.pdf")
    doc.InitSecurityHandler()
    image_counter= 0
    
    cos_doc = doc.GetSDFDoc()
    num_objs = cos_doc.XRefSize()
    i = 1
    while i < num_objs:
        obj = cos_doc.GetObj(i)
        if(obj is not None and not obj.IsFree() and obj.IsStream()):
            
            # Process only images
            itr = obj.Find("Type")
            
            if not itr.HasNext() or not itr.Value().GetName() == "XObject":
                i = i + 1
                continue
            
            itr = obj.Find("Subtype")
            if not itr.HasNext() or not itr.Value().GetName() == "Image":
                i = i + 1
                continue
            
            image = Image(obj)
            
            image_counter = image_counter + 1
            print("--> Image: " + str(image_counter))
            print("    Width: " + str(image.GetImageWidth()))
            print("    Height: " + str(image.GetImageHeight()))
            print("    BPC: " + str(image.GetBitsPerComponent()))
            
            fname = "image_extract2_" + str(image_counter)
                
            path = output_path + fname
            image.Export(path)
            
            #path = output_path + fname + ".tif"
            #image.ExportAsTiff(path)
            
            #path = output_path + fname + ".png"
            #image.ExportAsPng(path)
        i = i + 1
    doc.Close()
    PDFNet.Terminate()
    print("Done.")
    
if __name__ == '__main__':
    main()
```

{% endcode %}
{% endtab %}

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

```ruby
#---------------------------------------------------------------------------------------
# Copyright (c) 2001-2023 by Apryse Software Inc. All Rights Reserved.
# Consult LICENSE.txt regarding license information.
#---------------------------------------------------------------------------------------

require '../../../PDFNetC/Lib/PDFNetRuby'
include PDFNetRuby
require '../../LicenseKey/RUBY/LicenseKey'

$stdout.sync = true

#-----------------------------------------------------------------------------------
# This sample illustrates one approach to PDF image extraction 
# using PDFNet.
# 
# Note: Besides direct image export, you can also convert PDF images 
# to GDI+ Bitmap, or extract uncompressed/compressed image data directly 
# using element.GetImageData() (e.g. as illustrated in ElementReaderAdv 
# sample project).
#-----------------------------------------------------------------------------------

$image_counter = 0

# Relative path to the folder containing the test files.
$input_path = "../../TestFiles/"
$output_path = "../../TestFiles/Output/"

def ImageExtract(reader)
	element = reader.Next()
	while !(element.nil?) do
		if (element.GetType() == Element::E_image or
			element.GetType() == Element::E_inline_image)

			$image_counter =$image_counter + 1
			puts "--> Image: " + $image_counter.to_s()
			puts "    Width: " + element.GetImageWidth().to_s()
			puts "    Height: " + element.GetImageHeight().to_s()
			puts "    BPC: " + element.GetBitsPerComponent().to_s()
			
			ctm = element.GetCTM()
			x2 = 1
			y2 = 1
			pt = Point.new(x2, y2)
			point = ctm.Mult(pt)
			puts "    Coords: x1=%.2f, y1=%.2f, x2=%.2f, y2=%.2f" % [ctm.m_h, ctm.m_v, point.x, point.y]
			
			if element.GetType() == Element::E_image
				image = Image.new(element.GetXObject())
				
				fname = "image_extract1_" + $image_counter.to_s()
				
				path = $output_path + fname
				image.Export(path)
				
				#path = $output_path + fname + ".tif"
				#image.ExportAsTiff(path)
				
				#path = $output_path + fname + ".png"
				#image.ExportAsPng(path)
			end
		elsif element.GetType() == Element::E_form
			reader.FormBegin()
			ImageExtract(reader)
			reader.End()	
		end		
		element = reader.Next()
	end
end

	# Initialize PDFNet
	PDFNet.Initialize(PDFTronLicense.Key)	
	
	# Example 1: 
	# Extract images by traversing the display list for 
	# every page. With this approach it is possible to obtain 
	# image positioning information and DPI.
	
	doc = PDFDoc.new($input_path + "newsletter.pdf")
	doc.InitSecurityHandler()
	
	reader = ElementReader.new()
	
	# Read every page
	itr = doc.GetPageIterator()
	while itr.HasNext() do
		reader.Begin(itr.Current())
		ImageExtract(reader)
		reader.End()
		itr.Next()
	end

	doc.Close()

	puts "Done."	
	puts "----------------------------------------------------------------"
	
	# Example 2: 
	# Extract images by scanning the low-level document.
	
	doc = PDFDoc.new($input_path + "newsletter.pdf")
	doc.InitSecurityHandler()
	$image_counter= 0
	
	cos_doc = doc.GetSDFDoc()
	num_objs = cos_doc.XRefSize()
	i = 1
	while i < num_objs do
		obj = cos_doc.GetObj(i)

		if !(obj.nil?) and !(obj.IsFree()) and obj.IsStream()
			# Process only images
			itr = obj.Find("Type")

			if !(itr.HasNext()) or !(itr.Value().GetName() == "XObject")
				i = i + 1
				next
			end
			
			itr = obj.Find("Subtype")
			if !(itr.HasNext()) or !(itr.Value().GetName() == "Image")
				i = i + 1
				next
			end
			
			image = Image.new(obj)
			$image_counter = $image_counter + 1
			puts "--> Image: " + $image_counter.to_s()
			puts "    Width: " + image.GetImageWidth().to_s()
			puts "    Height: " + image.GetImageHeight().to_s()
			puts "    BPC: " + image.GetBitsPerComponent().to_s()
			
			fname = "image_extract2_" + $image_counter.to_s()
				
			path = $output_path + fname
			image.Export(path)
			
			#path = $output_path + fname + ".tif"
			#image.ExportAsTiff(path)
			
			#path = $output_path + fname + ".png"
			#image.ExportAsPng(path)
		end
		i = i + 1
	end
	doc.Close()
	PDFNet.Terminate
	puts "Done."
```

{% endcode %}
{% endtab %}

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

```vb
'
' Copyright (c) 2001-2024 by Apryse Software Inc. All Rights Reserved.
'

Imports System
Imports System.Drawing
Imports System.Drawing.Imaging

Imports pdftron
Imports pdftron.Common
Imports PDFTRON.SDF
Imports pdftron.PDF

Module ImageExtractTestVB
	Dim pdfNetLoader As PDFNetLoader
	Sub New()
		pdfNetLoader = pdftron.PDFNetLoader.Instance()
	End Sub

	'-----------------------------------------------------------------------------------
	' This sample illustrates one approach to PDF image extraction 
	' using PDFNet.
	' 
	' Note: Besides direct image export, you can also convert PDF images 
	' to GDI+ Bitmap, or extract uncompressed/compressed image data directly 
	' using element.GetImageData() (as illustrated in ElementReaderAdv 
	' sample project).
	'-----------------------------------------------------------------------------------

	Dim image_counter As Integer = 0

	' Relative path to the folder containing test files.
	Dim input_path As String = "../../../../TestFiles/"
	Dim output_path As String = "../../../../TestFiles/Output/"


	Sub ImageExtract(ByRef reader As ElementReader)
		Dim element As Element = reader.Next()
		While (Not IsNothing(element))		 ' Read page contents
			Dim type As Element.Type = element.GetType()

			If type = element.Type.e_image Or type = element.Type.e_inline_image Then
				image_counter = image_counter + 1
				Console.WriteLine("--> Image: {0}", image_counter)
				Console.WriteLine("    Width: {0}", element.GetImageWidth())
				Console.WriteLine("    Height: {0}", element.GetImageHeight())
				Console.WriteLine("    BPC: {0}", element.GetBitsPerComponent())

				Dim ctm As Matrix2D = element.GetCTM()
				Dim x2 As Double = 1
				Dim y2 As Double = 1
				ctm.Mult(x2, y2)
				Console.WriteLine("    Coords: x1=" + String.Format("{0:N2}", ctm.m_h) + ", y1=" + String.Format("{0:N2}", ctm.m_v) + ", x2=" + String.Format("{0:N2}", x2) + ", y2=" + String.Format("{0:N2}", y2))

				If element.GetType() = element.Type.e_image Then
					Dim fname As String = output_path + "image_extract1_" + image_counter.ToString()
					Dim image As PDFTRON.PDF.Image = New PDFTRON.PDF.Image(element.GetXObject())
					image.Export(fname)					' or ExporAsPng() or ExporAsTiff() ...

					' Convert PDF bitmap to GDI+ Bitmap...
					' Dim bmp As Bitmap = element.GetBitmap()
					' bmp.Save(fname, ImageFormat.Png)
					' bmp.Dispose()

					' Instead of converting PDF images to a Bitmap, you can also extract 
					' uncompressed/compressed image data directly using element.GetImageData() 
					' as illustrated in ElementReaderAdv sample project.
				End If
			ElseIf type = element.Type.e_form Then
				reader.FormBegin()				   ' Process form XObjects
				ImageExtract(reader)
				reader.End()
			End If

			element = reader.Next()
		End While
	End Sub

	Sub Main()

		PDFNet.Initialize(PDFTronLicense.Key)

		' Example 1: 
		' Extract images by traversing the display list for 
		' every page. With this approach it is possible to obtain 
		' image positioning information and DPI.
		Try
			Using doc As PDFDoc = New PDFDoc(input_path + "newsletter.pdf")
				doc.InitSecurityHandler()
				Using reader As ElementReader = New ElementReader

					Dim itr As PageIterator = doc.GetPageIterator()
					While itr.HasNext()
						reader.Begin(itr.Current())
						ImageExtract(reader)
						reader.End()
						itr.Next()
					End While

				End Using
			End Using
			Console.WriteLine("Done.")
		Catch ex As PDFNetException
			Console.WriteLine(ex.Message)
		Catch ex As Exception
			MsgBox(ex.Message)
		End Try
		Console.WriteLine("----------------------------------------------------------------")

		' Example 2: 
		' Extract images by scanning the low-level document.
		Try
			Using doc As PDFDoc = New PDFDoc(input_path + "newsletter.pdf")
				doc.InitSecurityHandler()
				image_counter = 0

				Dim cos_doc As SDFDoc = doc.GetSDFDoc()
				Dim num_objs As Integer = cos_doc.XRefSize()

				For i As Integer = 1 To num_objs - 1
					Dim obj As Obj = cos_doc.GetObj(i)
					If Not (obj Is Nothing Or obj.IsFree()) Then
						' Process only images
						If obj.IsStream() Then
							Dim itr As DictIterator = obj.Find("Type")
							If itr.HasNext() Then
								If itr.Value().GetName() = "XObject" Then
									itr = obj.Find("Subtype")
									If itr.HasNext() Then
										If itr.Value().GetName() = "Image" Then
											Dim image As pdftron.PDF.Image = New pdftron.PDF.Image(obj)

											image_counter = image_counter + 1
											Console.WriteLine("--> Image: {0}", image_counter)
											Console.WriteLine("    Width: {0}", image.GetImageWidth())
											Console.WriteLine("    Height: {0}", image.GetImageHeight())
											Console.WriteLine("    BPC: {0}", image.GetBitsPerComponent())

											Dim fname As String = output_path + "image_extract2_" + image_counter.ToString()
											image.Export(fname)		   ' or ExporAsPng() or ExporAsTiff() ...

											' Convert PDF bitmap to GDI+ Bitmap...
											' Dim bmp As Bitmap = element.GetBitmap()
											' bmp.Save(fname, ImageFormat.Png)
											' bmp.Dispose()

											' Instead of converting PDF images to a Bitmap, you can also extract 
											' uncompressed/compressed image data directly using element.GetImageData() 
											' as illustrated in ElementReaderAdv sample project.
										End If
									End If
								End If
							End If
						End If
					End If
				Next
			End Using
			Console.WriteLine("Done.")	
		Catch ex As PDFNetException
			Console.WriteLine(ex.Message)
		Catch ex As Exception
			MsgBox(ex.Message)
		End Try
		PDFNet.Terminate()
	End Sub
End Module
```

{% 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/core/get-started/samples/imageextracttest.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.
