> 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/pdfdrawtest.md).

# Convert to PDF to PNG, JPG, BMP or TIFF - PDFDraw

Learn to convert pdf to image format using WebViewer or programmatically using code without WebViewer UI.  Samples provided in Python, C++, C#, Java, Node.js (JavaScript), PHP, Ruby, Go and VB.

Sample code to use Apryse SDK's built-in rasterizer to render PDF images on the fly and save the resulting images in various raster image formats (such as PNG, JPEG, BMP, TIFF). Samples provided in Python, C++, C#, Java, Node.js (JavaScript), PHP, Ruby, Go and VB. Learn more about our [Server SDK](/core/get-started/get-started.md) and [PDF Conversion Library](/core/conversion/conversion.md).

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

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

using System;
using System.Drawing;
using System.Drawing.Imaging;
using System.Runtime.InteropServices;

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

namespace PDFDrawTestCS
{
	/// <summary>
	//---------------------------------------------------------------------------------------
	// The following sample illustrates how to convert PDF documents to various raster image 
	// formats (such as PNG, JPEG, BMP, TIFF), as well as how to convert a PDF page to GDI+ Bitmap 
	// for further manipulation and/or display in WinForms applications.
	//---------------------------------------------------------------------------------------
	/// </summary>
	class Class1
	{
		private static pdftron.PDFNetLoader pdfNetLoader = pdftron.PDFNetLoader.Instance();
		static Class1() {}
		
		/// <summary>
		/// The main entry point for the application.
		/// </summary>
		static void Main(string[] args)
		{
			// The first step in every application using PDFNet is to initialize the 
			// library and set the path to common PDF resources. The library is usually 
			// initialized only once, but calling Initialize() multiple times is also fine.
			PDFNet.Initialize(PDFTronLicense.Key);

			try 
			{
				// Optional: Set ICC color profiles to fine tune color conversion 
				// for PDF 'device' color spaces. You can use your own ICC profiles. 
				// Standard Adobe color profiles can be download from Adobes site: 
				// http://www.adobe.com/support/downloads/iccprofiles/iccprofiles_win.html
				//
				// Simply drop all *.icc files in PDFNet resource folder or you specify 
				// the full pathname.
				//---
				// PDFNet.SetResourcesPath("../../../../../resources");
				// PDFNet.SetColorManagement();
				// PDFNet.SetDefaultDeviceCMYKProfile("USWebCoatedSWOP.icc"); // will search in PDFNet resource folder.
				// PDFNet.SetDefaultDeviceRGBProfile("AdobeRGB1998.icc"); 

				// Optional: Set predefined font mappings to override default font 
				// substitution for documents with missing fonts. For example:
				//---
				// PDFNet.AddFontSubst("StoneSans-Semibold", "C:/WINDOWS/Fonts/comic.ttf");
				// PDFNet.AddFontSubst("StoneSans", "comic.ttf");  // search for 'comic.ttf' in PDFNet resource folder.
				// PDFNet.AddFontSubst(PDFNet.CharacterOrdering.e_Identity, "C:/WINDOWS/Fonts/arialuni.ttf");
				// PDFNet.AddFontSubst(PDFNet.CharacterOrdering.e_Japan1, "C:/Program Files/Adobe/Acrobat 7.0/Resource/CIDFont/KozMinProVI-Regular.otf");
				// PDFNet.AddFontSubst(PDFNet.CharacterOrdering.e_Japan2, "c:/myfonts/KozMinProVI-Regular.otf");
				//
				// If fonts are in PDFNet resource folder, it is not necessary to specify 
				// the full path name. For example,
				//---
				// PDFNet.AddFontSubst(PDFNet.CharacterOrdering.e_Korea1, "AdobeMyungjoStd-Medium.otf");
				// PDFNet.AddFontSubst(PDFNet.CharacterOrdering.e_CNS1, "AdobeSongStd-Light.otf");
				// PDFNet.AddFontSubst(PDFNet.CharacterOrdering.e_GB1, "AdobeMingStd-Light.otf");
			}
			catch (Exception)
			{
				Console.WriteLine("The specified color profile was not found.");
			}

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

			
			using (PDFDraw draw = new PDFDraw()) 
			{
				//--------------------------------------------------------------------------------
				// Example 1) Convert the first PDF page to PNG at 92 DPI. 
				// A three step tutorial to convert PDF page to an image.
				try  
				{
					// A) Open the PDF document.
					using (PDFDoc doc = new PDFDoc(input_path + "tiger.pdf")) 
					{
						// Initialize the security handler, in case the PDF is encrypted.
						doc.InitSecurityHandler();  

						// B) The output resolution is set to 92 DPI.
						draw.SetDPI(92);

						// C) Rasterize the first page in the document and save the result as PNG.
						Page pg = doc.GetPage(1);
						draw.Export(pg, output_path + "tiger_92dpi.png");

						Console.WriteLine("Example 1: tiger_92dpi.png");
						
						// Export the same page as TIFF
						draw.Export(pg, output_path + "tiger_92dpi.tif", "TIFF");
					}
				}
				catch (PDFNetException e) {
					Console.WriteLine(e.Message);
				}

				//--------------------------------------------------------------------------------
				// Example 2) Convert the all pages in a given document to JPEG at 72 DPI.
				ObjSet hint_set=new ObjSet(); // A collection of rendering 'hits'.
				Console.WriteLine("Example 2:");
				try  
				{
					using (PDFDoc doc = new PDFDoc(input_path + "newsletter.pdf")) 
					{
						// Initialize the security handler, in case the PDF is encrypted.
						doc.InitSecurityHandler();  
						
						draw.SetDPI(72); // Set the output resolution is to 72 DPI.
						
						// Use optional encoder parameter to specify JPEG quality.
						Obj encoder_param = hint_set.CreateDict();
						encoder_param.PutNumber("Quality", 80);
						
						// Traverse all pages in the document.
						for (PageIterator itr=doc.GetPageIterator(); itr.HasNext(); itr.Next()) 
						{
							string output_filename = string.Format("newsletter{0:d}.jpg", itr.GetPageNumber());
							Console.WriteLine("newsletter{0:d}.jpg", itr.GetPageNumber());
							draw.Export(itr.Current(), output_path + output_filename, "JPEG", encoder_param);
						}
					}

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

				try  // Examples 3-6
				{				
					// Common code for remaining samples.
					using (PDFDoc tiger_doc = new PDFDoc(input_path + "tiger.pdf")) 
					{
						// Initialize the security handler, in case the PDF is encrypted.
						tiger_doc.InitSecurityHandler();  
						Page page = tiger_doc.GetPage(1);

						//--------------------------------------------------------------------------------
						// Example 3) Convert the first page to GDI+ Bitmap. Also, rotate the 
						// page 90 degrees and save the result as RAW.
						draw.SetDPI(100); // Set the output resolution is to 100 DPI.
						draw.SetRotate(Page.Rotate.e_90);  // Rotate all pages 90 degrees clockwise.

						Bitmap bmp = draw.GetBitmap(page);

						// Save the raw RGB data to disk.
						string filename = "tiger_100dpi_rot90.raw";

						System.IO.File.WriteAllBytes(output_path + filename, BitmapToByteArray(bmp));

						Console.WriteLine("Example 3: tiger_100dpi_rot90.raw");
						draw.SetRotate(Page.Rotate.e_0);  // Disable image rotation for remaining samples.

						//--------------------------------------------------------------------------------
						// Example 4) Convert PDF page to a fixed image size. Also illustrates some 
						// other features in PDFDraw class such as rotation, image stretching, exporting 
						// to grayscale, or monochrome.

						// Initialize render 'gray_hint' parameter, that is used to control the 
						// rendering process. In this case we tell the rasterizer to export the image as 
						// 1 Bit Per Component (BPC) image.
						Obj mono_hint=hint_set.CreateDict();  
						mono_hint.PutNumber("BPC", 1);

						// SetImageSize can be used instead of SetDPI() to adjust page  scaling 
						// dynamically so that given image fits into a buffer of given dimensions.
						draw.SetImageSize(1000, 1000);		// Set the output image to be 1000 wide and 1000 pixels tall
						draw.Export(page, output_path + "tiger_1000x1000.png", "PNG", mono_hint);
						Console.WriteLine("Example 4: tiger_1000x1000.png");

						draw.SetImageSize(200, 400);		// Set the output image to be 200 wide and 300 pixels tall
						draw.SetRotate(Page.Rotate.e_180);  // Rotate all pages 90 degrees clockwise.

						// 'gray_hint' tells the rasterizer to export the image as grayscale.
						Obj gray_hint=hint_set.CreateDict();  
						gray_hint.PutName("ColorSpace", "Gray");

						draw.Export(page, output_path + "tiger_200x400_rot180.png", "PNG", gray_hint);
						Console.WriteLine("Example 4: tiger_200x400_rot180.png");

						draw.SetImageSize(400, 200, false);  // The third parameter sets 'preserve-aspect-ratio' to false.
						draw.SetRotate(Page.Rotate.e_0);	// Disable image rotation.
						draw.Export(page, output_path + "tiger_400x200_stretch.jpg", "JPEG");
						Console.WriteLine("Example 4: tiger_400x200_stretch.jpg");

						//--------------------------------------------------------------------------------
						// Example 5) Zoom into a specific region of the page and rasterize the 
						// area at 200 DPI and as a thumbnail (i.e. a 50x50 pixel image).
						page.SetCropBox(new Rect(216, 522, 330, 600));	// Set the page crop box.

						// Select the crop region to be used for drawing.
						draw.SetPageBox(Page.Box.e_crop); 
						draw.SetDPI(900);  // Set the output image resolution to 900 DPI.
						draw.Export(page, output_path + "tiger_zoom_900dpi.png", "PNG");
						Console.WriteLine("Example 5: tiger_zoom_900dpi.png");

						// -------------------------------------------------------------------------------
						// Example 6)
						draw.SetImageSize(50, 50);	   // Set the thumbnail to be 50x50 pixel image.
						draw.Export(page, output_path + "tiger_zoom_50x50.png", "PNG");
						Console.WriteLine("Example 6: tiger_zoom_50x50.png");
					}
				}
				catch (PDFNetException e) 
				{
					Console.WriteLine(e.Message);
				}

				Obj cmyk_hint = hint_set.CreateDict();
				cmyk_hint.PutName("ColorSpace", "CMYK");

				//--------------------------------------------------------------------------------
				// Example 7) Convert the first PDF page to CMYK TIFF at 92 DPI. 
				// A three step tutorial to convert PDF page to an image.
				try
				{
					// A) Open the PDF document.
					using (PDFDoc doc = new PDFDoc(input_path + "tiger.pdf")) 
					{
						// Initialize the security handler, in case the PDF is encrypted.
						doc.InitSecurityHandler();

						// B) The output resolution is set to 92 DPI.
						draw.SetDPI(92);

						// C) Rasterize the first page in the document and save the result as TIFF.
						Page pg = doc.GetPage(1);
						draw.Export(pg, output_path + "out1.tif", "TIFF", cmyk_hint);
						Console.WriteLine("Example 7: out1.tif");
					}
				}
				catch (PDFNetException e)
				{
					Console.WriteLine(e.Message);
				}

				//--------------------------------------------------------------------------------
				// Example 8) Export raster content to PNG using different image smoothing settings. 
				try
				{
					// A) Open the PDF document.
					using (PDFDoc doc = new PDFDoc(input_path + "tiger.pdf")) 
					{
						// Initialize the security handler, in case the PDF is encrypted.
						doc.InitSecurityHandler();

						// B) Get the page matrix 
						Page pg = doc.GetPage(1);
						Page.Box box = Page.Box.e_crop;
						Matrix2D mtx = pg.GetDefaultMatrix(true, box);
						// We want to render a quadrant, so use half of width and height
						double pg_w = pg.GetPageWidth(box) / 2;
						double pg_h = pg.GetPageHeight(box) / 2;

						// C) Scale matrix from PDF space to buffer space
						double dpi = 96.0;
						double scale = dpi / 72.0; // PDF space is 72 dpi
						int buf_w = (int) (Math.Floor(scale * pg_w));
						int buf_h = (int) (Math.Floor(scale * pg_h));
						int bytes_per_pixel = 4; // BGRA buffer
						int buf_size = buf_w * buf_h * bytes_per_pixel;
						mtx.Translate(0, -pg_h); // translate by '-pg_h' since we want south-west quadrant
						mtx = new Matrix2D(scale, 0, 0, scale, 0, 0) * mtx;

						// D) Rasterize page into memory buffer, according to our parameters
						byte[] buf;
						PDFRasterizer rast = new PDFRasterizer();
						buf = rast.Rasterize(pg, buf_w, buf_h, buf_w * bytes_per_pixel, bytes_per_pixel, true, mtx);

						// buf now contains raw BGRA bitmap.
						Console.WriteLine("Example 8: Successfully rasterized into memory buffer.");
					}
				}
				catch (PDFNetException e)
				{
					Console.WriteLine(e.Message);
				}
				//--------------------------------------------------------------------------------
				// Example 9) Export raster content to PNG using different image smoothing settings. 
				try
				{
					using (PDFDoc text_doc = new PDFDoc(input_path + "lorem_ipsum.pdf")) 
					{
						text_doc.InitSecurityHandler();

						draw.SetImageSmoothing(false, false);
						string filename = "raster_text_no_smoothing.png";
						draw.Export(text_doc.GetPageIterator().Current(), output_path + filename);
						Console.WriteLine("Example 9 a): " + filename + ". Done.");

						filename = "raster_text_smoothed.png";
						draw.SetImageSmoothing(true, false /*default quality bilinear resampling*/);
						draw.Export(text_doc.GetPageIterator().Current(), output_path + filename);
						Console.WriteLine("Example 9 b): " + filename + ". Done.");

						filename = "raster_text_high_quality.png";
						draw.SetImageSmoothing(true, true /*high quality area resampling*/);
						draw.Export(text_doc.GetPageIterator().Current(), output_path + filename);
						Console.WriteLine("Example 9 c): " + filename + ". Done.");
					}
				}
				catch (Exception e)
				{
					Console.WriteLine(e.Message);
				}

				//--------------------------------------------------------------------------------
				// Example 10) Export separations directly, without conversion to an output colorspace
				try
				{
					using (PDFDoc separation_doc = new PDFDoc(input_path + "op_blend_test.pdf"))
					{
						separation_doc.InitSecurityHandler();
						Obj separation_hint = hint_set.CreateDict();
						separation_hint.PutName("ColorSpace", "Separation");
						draw.SetDPI(96);
						draw.SetImageSmoothing(true, true);
						draw.SetOverprint(PDFRasterizer.OverprintPreviewMode.e_op_on);

						string filename = "merged_separations.png";
						draw.Export(separation_doc.GetPageIterator().Current(), output_path + filename, "PNG");
						Console.WriteLine("Example 10 a): " + filename + ". Done.");

						filename = "separation";
						draw.Export(separation_doc.GetPageIterator().Current(), output_path + filename, "PNG", separation_hint);
						Console.WriteLine("Example 10 b): " + filename + "_[ink].png. Done.");

						filename = "separation_NChannel.tif";
						draw.Export(separation_doc.GetPageIterator().Current(), output_path + filename, "TIFF", separation_hint);
						Console.WriteLine("Example 10 c): " + filename + ". Done.");
					}
				}
				catch (PDFNetException e)	
				{
					Console.WriteLine(e.Message);
				}

			}  // using PDFDraw
			PDFNet.Terminate();
		}

		public static byte[] BitmapToByteArray(Bitmap bitmap)
		{

			BitmapData bmpdata = null;

			try
			{
				bmpdata = bitmap.LockBits(new Rectangle(0, 0, bitmap.Width, bitmap.Height), ImageLockMode.ReadOnly, bitmap.PixelFormat);
				int numbytes = bmpdata.Stride * bitmap.Height;
				byte[] bytedata = new byte[numbytes];
				IntPtr ptr = bmpdata.Scan0;

				Marshal.Copy(ptr, bytedata, 0, numbytes);

				return bytedata;
			}
			finally
			{
				if (bmpdata != null)
					bitmap.UnlockBits(bmpdata);
			}
		} // end
	}
}
```

{% 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/PDFDraw.h>
#include <Filters/MappedFile.h>
#include <Filters/FilterWriter.h>
#include <cmath>
#include <string>
#include <iostream>
#include <fstream>
#include <sstream>
#include <SDF/ObjSet.h>
#include "../../LicenseKey/CPP/LicenseKey.h"

using namespace std;
using namespace pdftron;
using namespace PDF;
using namespace Filters;

//---------------------------------------------------------------------------------------
// The following sample illustrates how to convert PDF documents to various raster image 
// formats (such as PNG, JPEG, BMP, TIFF, etc), as well as how to convert a PDF page to 
// GDI+ Bitmap for further manipulation and/or display in WinForms applications.
//---------------------------------------------------------------------------------------
int main(int argc, char *argv[])
{
	try 
	{
		// The first step in every application using PDFNet is to initialize the 
		// library and set the path to common PDF resources. The library is usually 
		// initialized only once, but calling Initialize() multiple times is also fine.
		PDFNet::Initialize(LicenseKey);

		// Optional: Set ICC color profiles to fine tune color conversion 
		// for PDF 'device' color spaces...

		// PDFNet::SetResourcesPath("../../../resources");
		// PDFNet::SetColorManagement(PDFNet::e_lcms);
		// PDFNet::SetDefaultDeviceCMYKProfile("D:/Misc/ICC/USWebCoatedSWOP.icc");
		// PDFNet::SetDefaultDeviceRGBProfile("AdobeRGB1998.icc"); // will search in PDFNet resource folder.

		// ----------------------------------------------------
		// Optional: Set predefined font mappings to override default font 
		// substitution for documents with missing fonts...

		// PDFNet::AddFontSubst("StoneSans-Semibold", "C:/WINDOWS/Fonts/comic.ttf");
		// PDFNet::AddFontSubst("StoneSans", "comic.ttf");  // search for 'comic.ttf' in PDFNet resource folder.
		// PDFNet::AddFontSubst(PDFNet::e_Identity, "C:/WINDOWS/Fonts/arialuni.ttf");
		// PDFNet::AddFontSubst(PDFNet::e_Japan1, "C:/Program Files/Adobe/Acrobat 7.0/Resource/CIDFont/KozMinProVI-Regular.otf");
		// PDFNet::AddFontSubst(PDFNet::e_Japan2, "c:/myfonts/KozMinProVI-Regular.otf");
		// PDFNet::AddFontSubst(PDFNet::e_Korea1, "AdobeMyungjoStd-Medium.otf");
		// PDFNet::AddFontSubst(PDFNet::e_CNS1, "AdobeSongStd-Light.otf");
		// PDFNet::AddFontSubst(PDFNet::e_GB1, "AdobeMingStd-Light.otf");

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

		PDFDraw draw;  // PDFDraw class is used to rasterize PDF pages.

		//--------------------------------------------------------------------------------
		// Example 1) Convert the first page to PNG and TIFF at 92 DPI. 
		// A three step tutorial to convert PDF page to an image.
		try 
		{
			// A) Open the PDF document.
			PDFDoc doc((input_path + "tiger.pdf").c_str());

			// Initialize the security handler, in case the PDF is encrypted.
			doc.InitSecurityHandler();  

			// B) The output resolution is set to 92 DPI.
			draw.SetDPI(92);

			// C) Rasterize the first page in the document and save the result as PNG.
			draw.Export(doc.GetPageIterator().Current(), (output_path + "tiger_92dpi.png").c_str());

			cout << "Example 1: tiger_92dpi.png" << endl;

			// Export the same page as TIFF
			draw.Export(doc.GetPageIterator().Current(), (output_path + "tiger_92dpi.tif").c_str(), "TIFF");
		}
		catch(Common::Exception& e)	
		{
			cout << e << endl;
		}
		catch(...) 
		{
			cout << "Unknown Exception" << endl;
		}

		//--------------------------------------------------------------------------------
		// Example 2) Convert the all pages in a given document to JPEG at 72 DPI.
		cout << "Example 2:" << endl;
		SDF::ObjSet hint_set; //  A collection of rendering 'hits'.
		try 
		{
			PDFDoc doc((input_path + "newsletter.pdf").c_str());
			// Initialize the security handler, in case the PDF is encrypted.
			doc.InitSecurityHandler();  

			draw.SetDPI(72); // Set the output resolution is to 72 DPI.

			// Use optional encoder parameter to specify JPEG quality.
			SDF::Obj encoder_param=hint_set.CreateDict();
			encoder_param.PutNumber("Quality", 80);

			// Traverse all pages in the document.
			for (PageIterator itr=doc.GetPageIterator(); itr.HasNext(); itr.Next()) {
				ostringstream sstm;
				sstm << output_path << "newsletter" << itr.Current().GetIndex() << ".jpg";
				string path = sstm.str();
				cout << "newsletter" << itr.Current().GetIndex() << ".jpg" << endl;

				draw.Export(itr.Current(), path.c_str(), "JPEG", encoder_param);
			}

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


		// Examples 3-6
		try  
		{				
			// Common code for remaining samples.
			PDFDoc tiger_doc((input_path + "tiger.pdf").c_str());
			// Initialize the security handler, in case the PDF is encrypted.
			tiger_doc.InitSecurityHandler();  
			Page page = tiger_doc.GetPage(1);

			//--------------------------------------------------------------------------------
			// Example 3) Convert the first page to raw bitmap. Also, rotate the 
			// page 90 degrees and save the result as RAW.
			draw.SetDPI(100); // Set the output resolution is to 100 DPI.
			draw.SetRotate(Page::e_90);  // Rotate all pages 90 degrees clockwise.

			int width = 0, height = 0, stride = 0;
			double dpi = 0.0;
			const UChar* buf = draw.GetBitmap(page, width, height, stride, dpi, PDFDraw::e_rgb);

			
			// Save the raw RGB data to disk.
			ofstream outfile((output_path + "tiger_100dpi_rot90.raw").c_str(), ofstream::binary);
			outfile.write((char*)buf, height * stride);
			outfile.close();
			

			cout << "Example 3: tiger_100dpi_rot90.raw" << endl;
			draw.SetRotate(Page::e_0);  // Disable image rotation for remaining samples.

			//--------------------------------------------------------------------------------
			// Example 4) Convert PDF page to a fixed image size. Also illustrates some 
			// other features in PDFDraw class such as rotation, image stretching, exporting 
			// to grayscale, or monochrome.

			// Initialize render 'gray_hint' parameter, that is used to control the 
			// rendering process. In this case we tell the rasterizer to export the image as 
			// 1 Bit Per Component (BPC) image.
			SDF::Obj mono_hint=hint_set.CreateDict();  
			mono_hint.PutNumber("BPC", 1);

			// SetImageSize can be used instead of SetDPI() to adjust page  scaling 
			// dynamically so that given image fits into a buffer of given dimensions.
			draw.SetImageSize(1000, 1000);		// Set the output image to be 1000 wide and 1000 pixels tall
			draw.Export(page, (output_path + "tiger_1000x1000.png").c_str(), "PNG", mono_hint);
			cout << "Example 4: tiger_1000x1000.png" << endl;

			draw.SetImageSize(200, 400);	    // Set the output image to be 200 wide and 300 pixels tall
			draw.SetRotate(Page::e_180);  // Rotate all pages 90 degrees clockwise.

			// 'gray_hint' tells the rasterizer to export the image as grayscale.
			SDF::Obj gray_hint=hint_set.CreateDict();  
			gray_hint.PutName("ColorSpace", "Gray");

			draw.Export(page, (output_path + "tiger_200x400_rot180.png").c_str(), "PNG", gray_hint);
			cout << "Example 4: tiger_200x400_rot180.png" << endl;

			draw.SetImageSize(400, 200, false);  // The third parameter sets 'preserve-aspect-ratio' to false.
			draw.SetRotate(Page::e_0);    // Disable image rotation.
			draw.Export(page, (output_path + "tiger_400x200_stretch.jpg").c_str(), "JPEG");
			cout << "Example 4: tiger_400x200_stretch.jpg" << endl;

			//--------------------------------------------------------------------------------
			// Example 5) Zoom into a specific region of the page and rasterize the 
			// area at 200 DPI and as a thumbnail (i.e. a 50x50 pixel image).
			Rect zoom_rect(216, 522, 330, 600);
			page.SetCropBox(zoom_rect);	// Set the page crop box.

			// Select the crop region to be used for drawing.
			draw.SetPageBox(Page::e_crop); 
			draw.SetDPI(900);  // Set the output image resolution to 900 DPI.
			draw.Export(page, (output_path + "tiger_zoom_900dpi.png").c_str(), "PNG");
			cout << "Example 5: tiger_zoom_900dpi.png" << endl;

			// -------------------------------------------------------------------------------
			// Example 6)
			draw.SetImageSize(50, 50);	   // Set the thumbnail to be 50x50 pixel image.
			draw.Export(page, (output_path + "tiger_zoom_50x50.png").c_str(), "PNG");
			cout << "Example 6: tiger_zoom_50x50.png" << endl;
		}
		catch(Common::Exception& e)	
		{
			cout << e << endl;
		}
		catch(...) 
		{
			cout << "Unknown Exception" << endl;
		}

		

		//--------------------------------------------------------------------------------
		// Example 7) Convert the first PDF page to CMYK TIFF at 92 DPI.
		// A three step tutorial to convert PDF page to an image
		try 
		{
			pdftron::SDF::Obj cmyk_hint = hint_set.CreateDict();
			cmyk_hint.PutName("ColorSpace", "CMYK");
			// A) Open the PDF document.
			PDFDoc doc((input_path + "tiger.pdf").c_str());
			// Initialize the security handler, in case the PDF is encrypted.
			doc.InitSecurityHandler();  

			// B) The output resolution is set to 92 DPI.
			draw.SetDPI(92);

			// C) Rasterize the first page in the document and save the result as TIFF.
			Page pg = doc.GetPage(1);
			draw.Export(pg, output_path + "out1.tif", "TIFF", cmyk_hint);
			cout << "Example 7: out1.tif" << endl;
		}
		catch(Common::Exception& e)	
		{
			cout << e << endl;
		}
		catch(...) 
		{
			cout << "Unknown Exception" << endl;
		}

		//--------------------------------------------------------------------------------
		// Example 8) PDFRasterizer can be used for more complex rendering tasks, such as 
		// strip by strip or tiled document rendering. In particular, it is useful for 
		// cases where you cannot simply modify the page crop box (interactive viewing,
		// parallel rendering).  This example shows how you can rasterize the south-west
		// quadrant of a page.
		try 
		{
			// A) Open the PDF document.
			PDFDoc doc((input_path + "tiger.pdf").c_str());
			// Initialize the security handler, in case the PDF is encrypted.
			doc.InitSecurityHandler();  

			// B) Get the page matrix 
			Page pg = doc.GetPage(1);
			Page::Box box = Page::e_crop;
			Common::Matrix2D mtx = pg.GetDefaultMatrix(true, box);
			// We want to render a quadrant, so use half of width and height
			const double pg_w = pg.GetPageWidth(box) / 2;
			const double pg_h = pg.GetPageHeight(box) / 2;

			// C) Scale matrix from PDF space to buffer space
			const double dpi = 96.0;
			const double scale = dpi / 72.0; // PDF space is 72 dpi
			const int buf_w = static_cast<int>(floor(scale * pg_w));
			const int buf_h = static_cast<int>(floor(scale * pg_h));
			const int bytes_per_pixel = 4; // BGRA buffer
			const int buf_size = buf_w * buf_h * bytes_per_pixel;
			mtx.Translate(0, -pg_h); // translate by '-pg_h' since we want south-west quadrant
			mtx = Common::Matrix2D(scale, 0, 0, scale, 0, 0) * mtx;

			// D) Rasterize page into memory buffer, according to our parameters
			std::vector<unsigned char> buf;
			PDFRasterizer rast;
			buf = rast.Rasterize(pg, buf_w, buf_h, buf_w * bytes_per_pixel, bytes_per_pixel, true, mtx);

			// buf now contains raw BGRA bitmap.
			cout << "Example 8: Successfully rasterized into memory buffer." << endl;
		}
		catch(Common::Exception& e)	
		{
			cout << e << endl;
		}
		catch (...) {
			cout << "Unknown Exception" << endl;
		}
		//--------------------------------------------------------------------------------
		// Example 9) Export raster content to PNG using different image smoothing settings. 
		try 
		{
			PDFDoc text_doc((input_path + "lorem_ipsum.pdf").c_str());
			text_doc.InitSecurityHandler();

			draw.SetImageSmoothing(false, false);
			string filename = "raster_text_no_smoothing.png";
			draw.Export(text_doc.GetPageIterator().Current(), (output_path + filename).c_str());
			cout << "Example 9 a): " << filename << ". Done." << endl;

			filename = "raster_text_smoothed.png";
			draw.SetImageSmoothing(true, false /*default quality bilinear resampling*/);
			draw.Export(text_doc.GetPageIterator().Current(), (output_path + filename).c_str());
			cout << "Example 9 b): " << filename << ". Done." << endl;

			filename = "raster_text_high_quality.png";
			draw.SetImageSmoothing(true, true /*high quality area resampling*/);
			draw.Export(text_doc.GetPageIterator().Current(), (output_path + filename).c_str());
			cout << "Example 9 c): " << filename << ". Done." << endl;
		}
		catch(Common::Exception& e)	
		{
			cout << e << endl;
		}
		catch (...) {
			cout << "Unknown Exception" << endl;
		}
		//--------------------------------------------------------------------------------
		// Example 10) Export separations directly, without conversion to an output colorspace
		try
		{
			PDFDoc separation_doc((input_path + "op_blend_test.pdf").c_str());
			separation_doc.InitSecurityHandler();
			pdftron::SDF::Obj separation_hint = hint_set.CreateDict();
			separation_hint.PutName("ColorSpace", "Separation");
			draw.SetDPI(96);
			draw.SetImageSmoothing(true, true);
			draw.SetOverprint(PDFRasterizer::e_op_on);

			string filename = "merged_separations.png";
			draw.Export(separation_doc.GetPageIterator().Current(), (output_path + filename).c_str(), "PNG");
			cout << "Example 10 a): " << filename <<". Done." << endl;

			filename = "separation";
			draw.Export(separation_doc.GetPageIterator().Current(), (output_path + filename).c_str(), "PNG", separation_hint);
			cout << "Example 10 b): " << filename <<"_[ink].png. Done." << endl;

			filename = "separation_NChannel.tif";
			draw.Export(separation_doc.GetPageIterator().Current(), (output_path + filename).c_str(), "TIFF", separation_hint);
			cout << "Example 10 c): " << filename << ". Done." << endl;
		}
		catch(Common::Exception& e)	
		{
			cout << e << endl;
		}
		catch (...) {
			cout << "Unknown Exception" << endl;
		}
		PDFNet::Terminate();
	}
	catch(Common::Exception& e)	
	{
		cout << e << endl;
	}
	catch (...) {
		cout << "Unknown Exception" << endl;
	}

	return 0;	
}
```

{% 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"
	"os"
	. "pdftron"
)

import  "pdftron/Samples/LicenseKey/GO"

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

func main(){
    // The first step in every application using PDFNet is to initialize the 
    // library and set the path to common PDF resources. The library is usually 
    // initialized only once, but calling Initialize() multiple times is also fine.
    PDFNetInitialize(PDFTronLicense.Key)
    
    // Optional: Set ICC color profiles to fine tune color conversion 
    // for PDF 'device' color spaces...

    // PDFNetSetResourcesPath("../../../resources")
    // PDFNetSetColorManagement()
    // PDFNetSetDefaultDeviceCMYKProfile("D:/Misc/ICC/USWebCoatedSWOP.icc")
    // PDFNetSetDefaultDeviceRGBProfile("AdobeRGB1998.icc") // will search in PDFNet resource folder.

    // ----------------------------------------------------
    // Optional: Set predefined font mappings to override default font 
    // substitution for documents with missing fonts...

    // PDFNetAddFontSubst("StoneSans-Semibold", "C:/WINDOWS/Fonts/comic.ttf")
    // PDFNetAddFontSubst("StoneSans", "comic.ttf")  // search for 'comic.ttf' in PDFNet resource folder.
    // PDFNetAddFontSubst(PDFNetE_Identity, "C:/WINDOWS/Fonts/arialuni.ttf")
    // PDFNetAddFontSubst(PDFNetE_Japan1, "C:/Program Files/Adobe/Acrobat 7.0/Resource/CIDFont/KozMinProVI-Regular.otf")
    // PDFNetAddFontSubst(PDFNetE_Japan2, "c:/myfonts/KozMinProVI-Regular.otf")
    // PDFNetAddFontSubst(PDFNetE_Korea1, "AdobeMyungjoStd-Medium.otf")
    // PDFNetAddFontSubst(PDFNetE_CNS1, "AdobeSongStd-Light.otf")
    // PDFNetAddFontSubst(PDFNetE_GB1, "AdobeMingStd-Light.otf")
    
    //Example 1) Convert the first page to PNG and TIFF at 92 DPI.
    
    // PDFDraw class is used to rasterize PDF pages.
    draw := NewPDFDraw()
    
    //--------------------------------------------------------------------------------
    // Example 1) Convert the first page to PNG and TIFF at 92 DPI. 
    // A three step tutorial to convert PDF page to an image.
    
    // A) Open the PDF document.
    doc := NewPDFDoc(inputPath + "tiger.pdf")
    
    // Initialize the security handler, in case the PDF is encrypted.
    doc.InitSecurityHandler()
    
    // B) The output resolution is set to 92 DPI.
    draw.SetDPI(92)
    
    // C) Rasterize the first page in the document and save the result as PNG.
    itr := doc.GetPageIterator()
    draw.Export(itr.Current(), outputPath + "tiger_92dpi.png")
    
    fmt.Println("Example 1: tiger_92dpi.png")
    
    // Export the same page as TIFF
    itr = doc.GetPageIterator()
    draw.Export(itr.Current(), (outputPath + "tiger_92dpi.tif"), "TIFF")

    //--------------------------------------------------------------------------------
    // Example 2) Convert the all pages in a given document to JPEG at 72 DPI.

    fmt.Println("Example 2:")
    
    hintSet := NewObjSet() // A collection of rendering 'hits'.
    
    doc = NewPDFDoc(inputPath + "newsletter.pdf")
    // Initialize the security handler, in case the PDF is encrypted.
    doc.InitSecurityHandler()
    
    // Set the output resolution is to 72 DPI.
    draw.SetDPI(72)
    
    // Use optional encoder parameter to specify JPEG quality.
    encoderParam := hintSet.CreateDict()
    encoderParam.PutNumber("Quality", 80)
    
    // Traverse all pages in the document.
    itr = doc.GetPageIterator()
    for itr.HasNext(){
        filename := "newsletter" + strconv.Itoa(itr.Current().GetIndex()) + ".jpg"
        fmt.Println(filename)
        draw.Export(itr.Current(), outputPath + filename, "JPEG", encoderParam)
        itr.Next()
	}
    fmt.Println("Done.")

    // Examples 3-5
    // Common code for remaining samples.
    tigerDoc := NewPDFDoc(inputPath + "tiger.pdf")
    // Initialize the security handler, in case the PDF is encrypted.
    tigerDoc.InitSecurityHandler()
    page := tigerDoc.GetPage(1)
    
    //--------------------------------------------------------------------------------
    // Example 3) Convert the first page to raw bitmap. Also, rotate the 
    // page 90 degrees and save the result as RAW.
    draw.SetDPI(100)    // Set the output resolution is to 100 DPI.
    draw.SetRotate(PageE_90)   // Rotate all pages 90 degrees clockwise.
    bmp := draw.GetBitmap(page, PDFDrawE_rgb)
	bmpBytes := make([]byte, int(bmp.GetBuffer().Size()))
	buffVUC := bmp.GetBuffer()
	for i := 0; i < int(buffVUC.Size()); i++{
		bmpBytes[i] = buffVUC.Get(i)
	}
    // Save the raw RGB data to disk.
	f, err := os.Create(outputPath + "tiger_100dpi_rot90.raw")

    if err != nil {
        fmt.Println(err)
    }
    defer f.Close()
    _, err2 := f.Write(bmpBytes)
    if err2 != nil {
        fmt.Println(err2)
    }

    fmt.Println("Example 3: tiger_100dpi_rot90.raw")
    
    draw.SetRotate(PageE_0)    // Disable image rotation for remaining samples.
    
    //--------------------------------------------------------------------------------
    // Example 4) Convert PDF page to a fixed image size. Also illustrates some 
    // other features in PDFDraw class such as rotation, image stretching, exporting 
    // to grayscale, or monochrome.
    
    // Initialize render 'grayHint' parameter, that is used to control the 
    // rendering process. In this case we tell the rasterizer to export the image as 
    // 1 Bit Per Component (BPC) image.
    monoHint := hintSet.CreateDict()
    monoHint.PutNumber("BPC", 1)
    
    // SetImageSize can be used instead of SetDPI() to adjust page scaling
    // dynamically so that given image fits into a buffer of given dimensions.
    draw.SetImageSize(1000, 1000)   // Set the output image to be 1000 wide and 1000 pixels tall
    draw.Export(page, outputPath + "tiger_1000x1000.png", "PNG", monoHint)
    fmt.Println("Example 4: tiger_1000x1000.png")
    
    draw.SetImageSize(200, 400)     // Set the output image to be 200 wide and 400 pixels tall
    draw.SetRotate(PageE_180)      // Rotate all pages 90 degrees clockwise
    
    // 'grayHint' tells the rasterizer to export the image as grayscale.
    grayHint := hintSet.CreateDict()
    grayHint.PutName("ColorSpace", "Gray")
    
    draw.Export(page, (outputPath + "tiger_200x400_rot180.png"), "PNG", grayHint)
    fmt.Println("Example 4: tiger_200x400_rot180.png")
    
    draw.SetImageSize(400, 200, false)  // The third parameter sets 'preserve-aspect-ratio' to false
    draw.SetRotate(PageE_0)     // Disable image rotation
    draw.Export(page, outputPath + "tiger_400x200_stretch.jpg", "JPEG")
    fmt.Println("Example 4: tiger_400x200_stretch.jpg")
    
    //--------------------------------------------------------------------------------
    // Example 5) Zoom into a specific region of the page and rasterize the 
    // area at 200 DPI and as a thumbnail (i.e. a 50x50 pixel image).
    zoomRect := NewRect(216.0, 522.0, 330.0, 600.0)
    page.SetCropBox(zoomRect)    // Set the page crop box.

    // Select the crop region to be used for drawing.
    draw.SetPageBox(PageE_crop)
    draw.SetDPI(900)  // Set the output image resolution to 900 DPI.
    draw.Export(page, outputPath + "tiger_zoom_900dpi.png", "PNG")
    fmt.Println("Example 5: tiger_zoom_900dpi.png")

    // -------------------------------------------------------------------------------
    // Example 6)
    draw.SetImageSize(50, 50)      // Set the thumbnail to be 50x50 pixel image.
    draw.Export(page, outputPath + "tiger_zoom_50x50.png", "PNG")
    fmt.Println("Example 6: tiger_zoom_50x50.png")

    cmykHint := hintSet.CreateDict()
    cmykHint.PutName("ColorSpace", "CMYK")
    
    //--------------------------------------------------------------------------------
    // Example 7) Convert the first PDF page to CMYK TIFF at 92 DPI.
    // A three step tutorial to convert PDF page to an image
    // A) Open the PDF document
    doc = NewPDFDoc(inputPath + "tiger.pdf")
    // Initialize the security handler, in case the PDF is encrypted.
    doc.InitSecurityHandler()
    
    // The output resolution is set to 92 DPI.
    draw.SetDPI(92)
    
    // C) Rasterize the first page in the document and save the result as TIFF.
    pg := doc.GetPage(1)
    draw.Export(pg, outputPath + "out1.tif", "TIFF", cmykHint)
    fmt.Println("Example 7: out1.tif")
        
    doc.Close()

    // A) Open the PDF document.
    doc = NewPDFDoc(inputPath + "tiger.pdf");
    // Initialize the security handler, in case the PDF is encrypted.
    doc.InitSecurityHandler();  

    // B) Get the page matrix 
    pg = doc.GetPage(1);
    box := PageE_crop;
    mtx := pg.GetDefaultMatrix(true, box);
    // We want to render a quadrant, so use half of width and height
    pgW := pg.GetPageWidth(box) / 2;
    pgH := pg.GetPageHeight(box) / 2;

    // C) Scale matrix from PDF space to buffer space
    dpi := 96.0;
    scale := dpi / 72.0; // PDF space is 72 dpi
    bufW := int(scale * pgW);
    bufH := int(scale * pgH);
    bytesPerPixel := 4; // BGRA buffer
    bufSize := bufW * bufH * bytesPerPixel;
    mtx.Translate(0, -pgH); // translate by '-pgH' since we want south-west quadrant
    mtx = NewMatrix2D(scale, 0.0, 00.0, scale, 00.0, 00.0).Multiply(mtx);

    // D) Rasterize page into memory buffer, according to our parameters
    rast := NewPDFRasterizer();
    buf := rast.Rasterize(pg, bufW, bufH, bufW * bytesPerPixel, bytesPerPixel, true, mtx);
	if(bufSize != 0 && buf.Size() != 0){
		// buf now contains raw BGRA bitmap.
		fmt.Println("Example 8: Successfully rasterized into memory buffer.");
	}else{
		fmt.Println("Example 8: Failed to rasterize into memory buffer.");
	}

    //--------------------------------------------------------------------------------
    // Example 9) Export raster content to PNG using different image smoothing settings. 
    textDoc := NewPDFDoc(inputPath + "lorem_ipsum.pdf");
    textDoc.InitSecurityHandler();

    draw.SetImageSmoothing(false, false);
    filename := "raster_text_no_smoothing.png";
    draw.Export(textDoc.GetPageIterator().Current(), outputPath + filename);
    fmt.Println("Example 9 a): " + filename + ". Done.");

    filename = "raster_text_smoothed.png";
    draw.SetImageSmoothing(true, false); // second argument = default quality bilinear resampling
    draw.Export(textDoc.GetPageIterator().Current(), outputPath + filename);
    fmt.Println("Example 9 b): " + filename + ". Done.");

    filename = "raster_text_high_quality.png";
    draw.SetImageSmoothing(true, true); // second argument = default quality bilinear resampling
    draw.Export(textDoc.GetPageIterator().Current(), outputPath + filename);
    fmt.Println("Example 9 c): " + filename + ". Done.");

    //--------------------------------------------------------------------------------
    // Example 10) Export separations directly, without conversion to an output colorspace

    separationDoc := NewPDFDoc(inputPath + "op_blend_test.pdf");
    separationDoc.InitSecurityHandler();
    separationHint := hintSet.CreateDict();
    separationHint.PutName("ColorSpace", "Separation");
    draw.SetDPI(96);
    draw.SetImageSmoothing(true, true);
    draw.SetOverprint(PDFRasterizerE_op_on);

    filename = "merged_separations.png";
    draw.Export(separationDoc.GetPageIterator().Current(), outputPath + filename, "PNG");
    fmt.Println("Example 10 a): " + filename + ". Done.");

    filename = "separation";
    draw.Export(separationDoc.GetPageIterator().Current(), outputPath + filename, "PNG", separationHint);
    fmt.Println("Example 10 b): " + filename + "_[ink].png. Done.");

    filename = "separation_NChannel.tif";
    draw.Export(separationDoc.GetPageIterator().Current(), outputPath + filename, "TIFF", separationHint);
    fmt.Println("Example 10 c): " + filename + ". Done.");
    PDFNetTerminate()
}
```

{% 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 java.awt.image.PixelGrabber;

//import com.pdftron.filters.FilterWriter;
//import com.pdftron.filters.MappedFile;
import com.pdftron.pdf.*;
import com.pdftron.sdf.Obj;
import com.pdftron.sdf.ObjSet;
import com.pdftron.common.Matrix2D;
import com.pdftron.common.PDFNetException;

import java.io.FileOutputStream;
import java.io.File;
import java.nio.ByteBuffer;
import java.nio.IntBuffer;

//---------------------------------------------------------------------------------------
// The following sample illustrates how to convert PDF documents to various raster image 
// formats (such as PNG, JPEG, BMP, TIFF, etc), as well as how to convert a PDF page to 
// GDI+ Bitmap for further manipulation and/or display in WinForms applications.
//---------------------------------------------------------------------------------------
public class PDFDrawTest {
    public static void main(String[] args) {
        try {
            // The first step in every application using PDFNet is to initialize the
            // library and set the path to common PDF resources. The library is usually
            // initialized only once, but calling Initialize() multiple times is also fine.
            PDFNet.initialize(PDFTronLicense.Key());

            // Optional: Set ICC color profiles to fine tune color conversion
            // for PDF 'device' color spaces...

            //PDFNet.setResourcesPath("../../../resources");
            //PDFNet.setColorManagement();
            //PDFNet.setDefaultDeviceCMYKProfile("D:/Misc/ICC/USWebCoatedSWOP.icc");
            //PDFNet.setDefaultDeviceRGBProfile("AdobeRGB1998.icc"); // will search in PDFNet resource folder.

            // ----------------------------------------------------
            // Optional: Set predefined font mappings to override default font
            // substitution for documents with missing fonts...

            // PDFNet.addFontSubst("StoneSans-Semibold", "C:/WINDOWS/Fonts/comic.ttf");
            // PDFNet.addFontSubst("StoneSans", "comic.ttf");  // search for 'comic.ttf' in PDFNet resource folder.
            // PDFNet.addFontSubst(PDFNet.e_Identity, "C:/WINDOWS/Fonts/arialuni.ttf");
            // PDFNet.addFontSubst(PDFNet.e_Japan1, "C:/Program Files/Adobe/Acrobat 7.0/Resource/CIDFont/KozMinProVI-Regular.otf");
            // PDFNet.addFontSubst(PDFNet.e_Japan2, "c:/myfonts/KozMinProVI-Regular.otf");
            // PDFNet.addFontSubst(PDFNet.e_Korea1, "AdobeMyungjoStd-Medium.otf");
            // PDFNet.addFontSubst(PDFNet.e_CNS1, "AdobeSongStd-Light.otf");
            // PDFNet.addFontSubst(PDFNet.e_GB1, "AdobeMingStd-Light.otf");

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

            PDFDraw draw = new PDFDraw();  // PDFDraw class is used to rasterize PDF pages.
            ObjSet hint_set = new ObjSet();

            //--------------------------------------------------------------------------------
            // Example 1) Convert the first page to PNG and TIFF at 92 DPI.
            // A three step tutorial to convert PDF page to an image.
            try (PDFDoc doc = new PDFDoc((input_path + "tiger.pdf"))) {
                // A) Open the PDF document.

                // Initialize the security handler, in case the PDF is encrypted.
                doc.initSecurityHandler();

                // B) The output resolution is set to 92 DPI.
                draw.setDPI(92);

                // C) Rasterize the first page in the document and save the result as PNG.
                Page pg = doc.getPage(1);
                draw.export(pg, (output_path + "tiger_92dpi.png"));
                // output "tiger_92dpi.png"

                System.out.println("Example 1: tiger_92dpi.png");

                // Export the same page as TIFF
                draw.export(pg, (output_path + "tiger_92dpi.tif"), "TIFF");
                // output "tiger_92dpi.tif"
            } catch (Exception e) {
                e.printStackTrace();
            }

            //--------------------------------------------------------------------------------
            // Example 2) Convert the all pages in a given document to JPEG at 72 DPI.
            System.out.println("Example 2:");
            try (PDFDoc doc = new PDFDoc((input_path + "newsletter.pdf"))) {
                // Initialize the security handler, in case the PDF is encrypted.
                doc.initSecurityHandler();

                draw.setDPI(72); // Set the output resolution is to 72 DPI.

                // Use optional encoder parameter to specify JPEG quality.
                Obj encoder_param = hint_set.createDict();
                encoder_param.putNumber("Quality", 80);

                // Traverse all pages in the document.
                for (PageIterator itr = doc.getPageIterator(); itr.hasNext(); ) {
                    Page current = itr.next();
                    String filename = "newsletter" + current.getIndex() + ".jpg";
                    System.out.println(filename);
                    draw.export(current, output_path + filename, "JPEG", encoder_param);
                }

                System.out.println("Done.");
            } catch (Exception e) {
                e.printStackTrace();
            }

            FileOutputStream fos = null;
            // Examples 3-5
            try (PDFDoc tiger_doc = new PDFDoc((input_path + "tiger.pdf"))) {
                // Common code for remaining samples.
                // Initialize the security handler, in case the PDF is encrypted.
                tiger_doc.initSecurityHandler();
                Page page = tiger_doc.getPageIterator().next();

                //--------------------------------------------------------------------------------
                // Example 3) Convert the first page to raw bitmap. Also, rotate the
                // page 90 degrees and save the result as RAW.
                draw.setDPI(100); // Set the output resolution is to 100 DPI.
                draw.setRotate(Page.e_90);  // Rotate all pages 90 degrees clockwise.

                // create a Java image
                java.awt.Image image = draw.getBitmap(page);

                //
                int width = image.getWidth(null), height = image.getHeight(null);
                int[] arr = new int[width * height];
                PixelGrabber pg = new PixelGrabber(image, 0, 0, width, height, arr, 0, width);
                pg.grabPixels();

                // convert to byte array
                ByteBuffer byteBuffer = ByteBuffer.allocate(arr.length * 4);
                IntBuffer intBuffer = byteBuffer.asIntBuffer();
                intBuffer.put(arr);
                byte[] rawByteArray = byteBuffer.array();
                // finally write the file
                fos = new FileOutputStream(output_path + "tiger_100dpi_rot90.raw");
                fos.write(rawByteArray);
                System.out.println("Example 3: tiger_100dpi_rot90.raw");

                draw.setRotate(Page.e_0);  // Disable image rotation for remaining samples.

                //--------------------------------------------------------------------------------
                // Example 4) Convert PDF page to a fixed image size. Also illustrates some
                // other features in PDFDraw class such as rotation, image stretching, exporting
                // to grayscale, or monochrome.

                // Initialize render 'gray_hint' parameter, that is used to control the
                // rendering process. In this case we tell the rasterizer to export the image as
                // 1 Bit Per Component (BPC) image.
                Obj mono_hint = hint_set.createDict();
                mono_hint.putNumber("BPC", 1);

                // SetImageSize can be used instead of SetDPI() to adjust page  scaling
                // dynamically so that given image fits into a buffer of given dimensions.
                draw.setImageSize(1000, 1000);        // Set the output image to be 1000 wide and 1000 pixels tall

                draw.export(page, (output_path + "tiger_1000x1000.png"), "PNG", mono_hint);
                System.out.println("Example 4: tiger_1000x1000.png");

                draw.setImageSize(200, 400); // Set the output image to be 200 wide and 300 pixels tall
                draw.setRotate(Page.e_180); // Rotate all pages 90 degrees clockwise.

                // 'gray_hint' tells the rasterizer to export the image as grayscale.
                Obj gray_hint = hint_set.createDict();
                gray_hint.putName("ColorSpace", "Gray");

                draw.export(page, (output_path + "tiger_200x400_rot180.png"), "PNG", gray_hint);
                System.out.println("Example 4: tiger_200x400_rot180.png");

                draw.setImageSize(400, 200, false);  // The third parameter sets 'preserve-aspect-ratio' to false.
                draw.setRotate(Page.e_0);    // Disable image rotation.
                draw.export(page, (output_path + "tiger_400x200_stretch.jpg"), "JPEG");
                // output "tiger_400x200_stretch.jpg"
                System.out.println("Example 4: tiger_400x200_stretch.jpg");

                //--------------------------------------------------------------------------------
                // Example 5) Zoom into a specific region of the page and rasterize the
                // area at 200 DPI and as a thumbnail (i.e. a 50x50 pixel image).
                Rect zoom_rect = new Rect(216, 522, 330, 600);
                page.setCropBox(zoom_rect);    // Set the page crop box.

                // Select the crop region to be used for drawing.
                draw.setPageBox(Page.e_crop);
                draw.setDPI(900);  // Set the output image resolution to 900 DPI.
                draw.export(page, (output_path + "tiger_zoom_900dpi.png"), "PNG");
                // output "tiger_zoom_900dpi.png"
                System.out.println("Example 5: tiger_zoom_900dpi.png");

                // -------------------------------------------------------------------------------
                // Example 6)
                draw.setImageSize(50, 50);       // Set the thumbnail to be 50x50 pixel image.
                draw.export(page, (output_path + "tiger_zoom_50x50.png"), "PNG");
                // output "tiger_zoom_50x50.png"
                System.out.println("Example 6: tiger_zoom_50x50.png");
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                if (fos != null) {
                    try {
                        fos.close();
                    } catch (Exception ignored) {
                    }
                }
            }

            Obj cmyk_hint = hint_set.createDict();
            cmyk_hint.putName("ColorSpace", "CMYK");

            //--------------------------------------------------------------------------------
            // Example 7) Convert the first PDF page to CMYK TIFF at 92 DPI.
            // A three step tutorial to convert PDF page to an image
            try (PDFDoc doc = new PDFDoc(input_path + "tiger.pdf")) {
                // A) Open the PDF document.

                // Initialize the security handler, in case the PDF is encrypted.
                doc.initSecurityHandler();

                // B) The output resolution is set to 92 DPI.
                draw.setDPI(92);

                // C) Rasterize the first page in the document and save the result as TIFF.
                Page pg = doc.getPage(1);
                draw.export(pg, output_path + "out1.tif", "TIFF", cmyk_hint);
                // output "out1.tif"
                System.out.println("Example 7: out1.tif");
            } catch (Exception e) {
                e.printStackTrace();
            }

            //--------------------------------------------------------------------------------
            // Example 8) PDFRasterizer can be used for more complex rendering tasks, such as 
            // strip by strip or tiled document rendering. In particular, it is useful for 
            // cases where you cannot simply modify the page crop box (interactive viewing,
            // parallel rendering).  This example shows how you can rasterize the south-west
            // quadrant of a page.
            try (PDFDoc doc = new PDFDoc(input_path + "tiger.pdf")) {
                // A) Open the PDF document.
                // Initialize the security handler, in case the PDF is encrypted.
                doc.initSecurityHandler();

                // B) Get the page matrix 
                Page pg = doc.getPage(1);
                int box = Page.e_crop;
                Matrix2D mtx = pg.getDefaultMatrix(true, box, 0);
                // We want to render a quadrant, so use half of width and height
                double pg_w = pg.getPageWidth(box) / 2;
                double pg_h = pg.getPageHeight(box) / 2;

                // C) Scale matrix from PDF space to buffer space
                double dpi = 96.0;
                double scale = dpi / 72.0; // PDF space is 72 dpi
                double buf_w = Math.floor(scale * pg_w);
                double buf_h = Math.floor(scale * pg_h);
                int bytes_per_pixel = 4; // BGRA buffer
                mtx.translate(0, -pg_h); // translate by '-pg_h' since we want south-west quadrant
                mtx = (new Matrix2D(scale, 0, 0, scale, 0, 0)).multiply(mtx);

                // D) Rasterize page into memory buffer, according to our parameters
                PDFRasterizer rast = new PDFRasterizer();
                byte[] buf = rast.rasterize(pg, (int) buf_w, (int) buf_h, (int) buf_w * bytes_per_pixel, bytes_per_pixel, true, mtx, null);

                System.out.println("Example 8: Successfully rasterized into memory buffer.");
            } catch (Exception e) {
                e.printStackTrace();
            }

            //--------------------------------------------------------------------------------
            // Example 9) Export raster content to PNG using different image smoothing settings.
            try (PDFDoc text_doc = new PDFDoc(input_path + "lorem_ipsum.pdf")) {
                text_doc.initSecurityHandler();

                draw.setImageSmoothing(false, false);
                String filename = "raster_text_no_smoothing.png";
                draw.export(text_doc.getPageIterator().next(), output_path + filename);
                System.out.println("Example 9 a): " + filename + ". Done.");

                filename = "raster_text_smoothed.png";
                draw.setImageSmoothing(true, false /*default quality bilinear resampling*/);
                draw.export(text_doc.getPageIterator().next(), output_path + filename);
                System.out.println("Example 9 b): " + filename + ". Done.");

                filename = "raster_text_high_quality.png";
                draw.setImageSmoothing(true, true /*high quality area resampling*/);
                draw.export(text_doc.getPageIterator().next(), output_path + filename);
                System.out.println("Example 9 c): " + filename + ". Done.");
            } catch (Exception e) {
                e.printStackTrace();
            }


            //--------------------------------------------------------------------------------
            // Example 10) Export separations directly, without conversion to an output colorspace
            try (PDFDoc separation_doc = new PDFDoc(input_path + "op_blend_test.pdf")) {
                separation_doc.initSecurityHandler();

                Obj separation_hint = hint_set.createDict();
                separation_hint.putName("ColorSpace", "Separation");
                draw.setDPI(96);
                draw.setImageSmoothing(true, true);
                // set overprint preview to always on
                draw.setOverprint(1);

                String filename = new String("merged_separations.png");
                draw.export(separation_doc.getPage(1), output_path + filename, "PNG");
                System.out.println("Example 10 a): " + filename + ". Done.");

                filename = new String("separation");
                draw.export(separation_doc.getPage(1), output_path + filename, "PNG", separation_hint);
                System.out.println("Example 10 b): " + filename + "_[ink].png. Done.");

                filename = new String("separation_NChannel.tif");
                draw.export(separation_doc.getPage(1), output_path + filename, "TIFF", separation_hint);
                System.out.println("Example 10 c): " + filename + ". Done.");
            } catch (Exception e) {
                e.printStackTrace();
            }

            // Calling Terminate when PDFNet is no longer in use is a good practice, but
            // is not required.
            PDFNet.terminate();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
```

{% 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.
//---------------------------------------------------------------------------------------

//---------------------------------------------------------------------------------------
// The following sample illustrates how to convert PDF documents to various raster image 
// formats (such as PNG, JPEG, BMP, TIFF, etc), as well as how to convert a PDF page to 
// GDI+ Bitmap for further manipulation and/or display in WinForms applications.
//---------------------------------------------------------------------------------------

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

((exports) => {

  exports.runPDFDrawTest = () => {

    const main = async () => {
      // Relative path to the folder containing test files.
      const inputPath = '../TestFiles/';
      const outputPath = inputPath + 'Output/';

      try {

        // Optional: Set ICC color profiles to fine tune color conversion 
        // for PDF 'device' color spaces...

        // PDFNet.setResourcesPath('../resources');
        // PDFNet.setColorManagement(PDFNet.CMSType.e_lcms);
        // PDFNet.setDefaultDeviceCMYKProfile('D:/Misc/ICC/USWebCoatedSWOP.icc');
        // PDFNet.setDefaultDeviceRGBProfile('AdobeRGB1998.icc'); // will search in PDFNet resource folder.

        // ----------------------------------------------------
        // Optional: Set predefined font mappings to override default font 
        // substitution for documents with missing fonts...

        // PDFNet.addFontSubst('StoneSans-Semibold', 'C:/WINDOWS/Fonts/comic.ttf');
        // PDFNet.addFontSubst('StoneSans', 'comic.ttf');  // search for 'comic.ttf' in PDFNet resource folder.
        // PDFNet.addFontSubst(PDFNet.CharacterOrdering.e_Identity, 'C:/WINDOWS/Fonts/arialuni.ttf');
        // PDFNet.addFontSubst(PDFNet.CharacterOrdering.e_Japan1, 'C:/Program Files/Adobe/Acrobat 7.0/Resource/CIDFont/KozMinProVI-Regular.otf');
        // PDFNet.addFontSubst(PDFNet.CharacterOrdering.e_Japan2, 'c:/myfonts/KozMinProVI-Regular.otf');
        // PDFNet.addFontSubst(PDFNet.CharacterOrdering.e_Korea1, 'AdobeMyungjoStd-Medium.otf');
        // PDFNet.addFontSubst(PDFNet.CharacterOrdering.e_CNS1, 'AdobeSongStd-Light.otf');
        // PDFNet.addFontSubst(PDFNet.CharacterOrdering.e_GB1, 'AdobeMingStd-Light.otf');

        const draw = await PDFNet.PDFDraw.create();  // PDFDraw class is used to rasterize PDF pages.

        //--------------------------------------------------------------------------------
        // Example 1) Convert the first page to PNG and TIFF at 92 DPI. 
        // A three step tutorial to convert PDF page to an image.
        try {
          // A) Open the PDF document.
          const doc = await PDFNet.PDFDoc.createFromFilePath(inputPath + 'tiger.pdf');

          // Initialize the security handler, in case the PDF is encrypted.
          doc.initSecurityHandler();

          // B) The output resolution is set to 92 DPI.
          draw.setDPI(92);

          const firstPage = await (await doc.getPageIterator()).current();
          // C) Rasterize the first page in the document and save the result as PNG.
          await draw.export(firstPage, outputPath + 'tiger_92dpi.png');

          console.log('Example 1: tiger_92dpi.png');

          // Export the same page as TIFF
          await draw.export(firstPage, outputPath + 'tiger_92dpi.tif', 'TIFF');
        } catch (err) {
          console.log(err);
        }

        //--------------------------------------------------------------------------------
        // Example 2) Convert the all pages in a given document to JPEG at 72 DPI.
        console.log('Example 2:');
        const hint_set = await PDFNet.ObjSet.create(); //  A collection of rendering 'hits'.
        try {
          const doc = await PDFNet.PDFDoc.createFromFilePath(inputPath + 'newsletter.pdf');
          // Initialize the security handler, in case the PDF is encrypted.
          doc.initSecurityHandler();

          draw.setDPI(72); // Set the output resolution is to 72 DPI.

          // Use optional encoder parameter to specify JPEG quality.
          const encoderParam = await hint_set.createDict();
          await encoderParam.putNumber('Quality', 80);

          // Traverse all pages in the document.
          for (const itr = await doc.getPageIterator(); await itr.hasNext(); await itr.next()) {
            const currPage = await itr.current();
            const currPageIdx = await currPage.getIndex();
            const path = outputPath + 'newsletter' + currPageIdx + '.jpg';
            console.log('newsletter' + currPageIdx + '.jpg');

            await draw.export(currPage, path, 'JPEG', encoderParam);
          }
          console.log('Done.');
        } catch (err) {
          console.log(err);
        }

        // Examples 3-6
        try {
          // Common code for remaining samples.
          const tiger_doc = await PDFNet.PDFDoc.createFromFilePath(inputPath + 'tiger.pdf');
          // Initialize the security handler, in case the PDF is encrypted.
          tiger_doc.initSecurityHandler();
          const page = await tiger_doc.getPage(1);

          //--------------------------------------------------------------------------------
          // Example 3) Convert the first page to raw bitmap. Also, rotate the 
          // page 90 degrees and save the result as RAW.
          draw.setDPI(100); // Set the output resolution is to 100 DPI.
          draw.setRotate(PDFNet.Page.Rotate.e_90);  // Rotate all pages 90 degrees clockwise.

          const bitmapInfo = await draw.getBitmap(page, PDFNet.PDFDraw.PixelFormat.e_rgb, false);
          const buf = Buffer.from(bitmapInfo.buf, 0, bitmapInfo.height * bitmapInfo.stride)

          // Save the raw RGB data to disk.
          fs.appendFileSync(outputPath + 'tiger_100dpi_rot90.raw', buf, 'binary');

          console.log('Example 3: tiger_100dpi_rot90.raw');
          draw.setRotate(PDFNet.Page.Rotate.e_0);  // Disable image rotation for remaining samples.

          //--------------------------------------------------------------------------------
          // Example 4) Convert PDF page to a fixed image size. Also illustrates some 
          // other features in PDFDraw class such as rotation, image stretching, exporting 
          // to grayscale, or monochrome.

          // Initialize render 'gray_hint' parameter, that is used to control the 
          // rendering process. In this case we tell the rasterizer to export the image as 
          // 1 Bit Per Component (BPC) image.
          const mono_hint = await hint_set.createDict();
          await mono_hint.putNumber('BPC', 1);

          // SetImageSize can be used instead of SetDPI() to adjust page  scaling 
          // dynamically so that given image fits into a buffer of given dimensions.
          draw.setImageSize(1000, 1000);		// Set the output image to be 1000 wide and 1000 pixels tall
          draw.export(page, outputPath + 'tiger_1000x1000.png', 'PNG', mono_hint);
          console.log('Example 4: tiger_1000x1000.png');

          draw.setImageSize(200, 400);	    // Set the output image to be 200 wide and 300 pixels tall
          draw.setRotate(PDFNet.Page.Rotate.e_180);  // Rotate all pages 90 degrees clockwise.

          // 'gray_hint' tells the rasterizer to export the image as grayscale.
          const gray_hint = await hint_set.createDict();
          await gray_hint.putName('ColorSpace', 'Gray');

          await draw.export(page, outputPath + 'tiger_200x400_rot180.png', 'PNG', gray_hint);
          console.log('Example 4: tiger_200x400_rot180.png');

          draw.setImageSize(400, 200, false);  // The third parameter sets 'preserve-aspect-ratio' to false.
          draw.setRotate(PDFNet.Page.Rotate.e_0);    // Disable image rotation.
          await draw.export(page, outputPath + 'tiger_400x200_stretch.jpg', 'JPEG');
          console.log('Example 4: tiger_400x200_stretch.jpg');

          //--------------------------------------------------------------------------------
          // Example 5) Zoom into a specific region of the page and rasterize the 
          // area at 200 DPI and as a thumbnail (i.e. a 50x50 pixel image).
          const zoom_rect = await PDFNet.Rect.init(216, 522, 330, 600);
          await page.setCropBox(zoom_rect);	// Set the page crop box.

          // Select the crop region to be used for drawing.
          draw.setPageBox(PDFNet.Page.Box.e_crop);
          draw.setDPI(900);  // Set the output image resolution to 900 DPI.
          await draw.export(page, outputPath + 'tiger_zoom_900dpi.png', 'PNG');
          console.log('Example 5: tiger_zoom_900dpi.png');

          // -------------------------------------------------------------------------------
          // Example 6)
          draw.setImageSize(50, 50);	   // Set the thumbnail to be 50x50 pixel image.
          await draw.export(page, outputPath + 'tiger_zoom_50x50.png', 'PNG');
          console.log('Example 6: tiger_zoom_50x50.png');
        } catch (err) {
          console.log(err);
        }

        //--------------------------------------------------------------------------------
        // Example 7) Convert the first PDF page to CMYK TIFF at 92 DPI.
        // A three step tutorial to convert PDF page to an image
        try {
          const cmyk_hint = await hint_set.createDict();
          await cmyk_hint.putName('ColorSpace', 'CMYK');
          // A) Open the PDF document.
          const doc = await PDFNet.PDFDoc.createFromFilePath(inputPath + 'tiger.pdf');
          // Initialize the security handler, in case the PDF is encrypted.
          doc.initSecurityHandler();

          // B) The output resolution is set to 92 DPI.
          draw.setDPI(92);

          // C) Rasterize the first page in the document and save the result as TIFF.
          const pg = await doc.getPage(1);
          await draw.export(pg, outputPath + 'out1.tif', 'TIFF', cmyk_hint);
          console.log('Example 7: out1.tif');
        } catch (err) {
          console.log(err);
        }

        //--------------------------------------------------------------------------------
        // Example 8) PDFRasterizer can be used for more complex rendering tasks, such as 
        // strip by strip or tiled document rendering. In particular, it is useful for 
        // cases where you cannot simply modify the page crop box (interactive viewing,
        // parallel rendering).  This example shows how you can rasterize the south-west
        // quadrant of a page.
        try {
          // A) Open the PDF document.
          const doc = await PDFNet.PDFDoc.createFromFilePath(inputPath + 'tiger.pdf');
          // Initialize the security handler, in case the PDF is encrypted.
          doc.initSecurityHandler();

          // B) Get the page matrix 
          const pg = await doc.getPage(1);
          const box = PDFNet.Page.Rotate.e_crop;
          let mtx = await pg.getDefaultMatrix(true, box);
          // We want to render a quadrant, so use half of width and height
          const pg_w = await pg.getPageWidth(box) / 2;
          const pg_h = await pg.getPageHeight(box) / 2;

          // C) Scale matrix from PDF space to buffer space
          const dpi = 96.0;
          const scale = dpi / 72.0; // PDF space is 72 dpi
          const buf_w = Math.floor(scale * pg_w);
          const buf_h = Math.floor(scale * pg_h);
          const bytes_per_pixel = 4; // BGRA buffer
          await mtx.translate(0, -pg_h); // translate by '-pg_h' since we want south-west quadrant
          const scale_mtx = await PDFNet.Matrix2D.create(scale, 0, 0, scale, 0, 0);
          await scale_mtx.multiply(mtx);
          mtx = scale_mtx;

          // D) Rasterize page into memory buffer, according to our parameters
          const rast = await PDFNet.PDFRasterizer.create();
          const buf = await rast.rasterize(pg, buf_w, buf_h, buf_w * bytes_per_pixel, bytes_per_pixel, true, mtx);

          // buf now contains raw BGRA bitmap.
          console.log('Example 8: Successfully rasterized into memory buffer.');
        } catch (err) {
          console.log(err);
        }

        //--------------------------------------------------------------------------------
        // Example 9) Export raster content to PNG using different image smoothing settings. 
        try {
          const text_doc = await PDFNet.PDFDoc.createFromFilePath(inputPath + 'lorem_ipsum.pdf');
          text_doc.initSecurityHandler();
          const itr = await text_doc.getPageIterator();
          const page = await itr.current();

          draw.setImageSmoothing(false, false);
          let filename = 'raster_text_no_smoothing.png';
          await draw.export(page, outputPath + filename);
          console.log('Example 9 a): ' + filename + '. Done.');

          filename = 'raster_text_smoothed.png';
          draw.setImageSmoothing(true, false /*default quality bilinear resampling*/);
          await draw.export(page, outputPath + filename);
          console.log('Example 9 b): ' + filename + '. Done.');

          filename = 'raster_text_high_quality.png';
          draw.setImageSmoothing(true, true /*high quality area resampling*/);
          await draw.export(page, outputPath + filename);
          console.log('Example 9 c): ' + filename + '. Done.');
        } catch (err) {
          console.log(err);
        }

        //--------------------------------------------------------------------------------
        // Example 10) Export separations directly, without conversion to an output colorspace
        try {
          const separation_doc = await PDFNet.PDFDoc.createFromFilePath(inputPath + 'op_blend_test.pdf');
          separation_doc.initSecurityHandler();
          const separation_hint = await hint_set.createDict();
          await separation_hint.putName('ColorSpace', 'Separation');
          draw.setDPI(96);
          draw.setImageSmoothing(true, true);
          draw.setOverprint(PDFNet.PDFRasterizer.OverprintPreviewMode.e_op_on);

          const itr = await separation_doc.getPageIterator();
          const page = await itr.current();
          let filename = 'merged_separations.png';
          await draw.export(page, outputPath + filename, 'PNG');
          console.log('Example 10 a): ' + filename + '. Done.');

          filename = 'separation';
          await draw.export(page, outputPath + filename, 'PNG', separation_hint);
          console.log('Example 10 b): ' + filename + '_[ink].png. Done.');

          filename = 'separation_NChannel.tif';
          await draw.export(page, outputPath + filename, 'TIFF', separation_hint);
          console.log('Example 10 c): ' + filename + '. Done.');
        } catch (err) {
          console.log(err);
        }
      } 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.runPDFDrawTest();
})(exports);
// eslint-disable-next-line spaced-comment
//# sourceURL=PDFDrawTest.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 *

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

#---------------------------------------------------------------------------------------
# The following sample illustrates how to convert PDF documents to various raster image 
# formats (such as PNG, JPEG, BMP, TIFF, etc), as well as how to convert a PDF page to 
# GDI+ Bitmap for further manipulation and/or display in WinForms applications.
#---------------------------------------------------------------------------------------

def main():
    
    # The first step in every application using PDFNet is to initialize the 
    # library and set the path to common PDF resources. The library is usually 
    # initialized only once, but calling Initialize() multiple times is also fine.
    PDFNet.Initialize(LicenseKey)
    
    # Optional: Set ICC color profiles to fine tune color conversion 
    # for PDF 'device' color spaces...

    # PDFNet.SetResourcesPath("../../../resources")
    # PDFNet.SetColorManagement()
    # PDFNet.SetDefaultDeviceCMYKProfile("D:/Misc/ICC/USWebCoatedSWOP.icc")
    # PDFNet.SetDefaultDeviceRGBProfile("AdobeRGB1998.icc") # will search in PDFNet resource folder.

    # ----------------------------------------------------
    # Optional: Set predefined font mappings to override default font 
    # substitution for documents with missing fonts...

    # PDFNet.AddFontSubst("StoneSans-Semibold", "C:/WINDOWS/Fonts/comic.ttf")
    # PDFNet.AddFontSubst("StoneSans", "comic.ttf")  # search for 'comic.ttf' in PDFNet resource folder.
    # PDFNet.AddFontSubst(PDFNet.e_Identity, "C:/WINDOWS/Fonts/arialuni.ttf")
    # PDFNet.AddFontSubst(PDFNet.e_Japan1, "C:/Program Files/Adobe/Acrobat 7.0/Resource/CIDFont/KozMinProVI-Regular.otf")
    # PDFNet.AddFontSubst(PDFNet.e_Japan2, "c:/myfonts/KozMinProVI-Regular.otf")
    # PDFNet.AddFontSubst(PDFNet.e_Korea1, "AdobeMyungjoStd-Medium.otf")
    # PDFNet.AddFontSubst(PDFNet.e_CNS1, "AdobeSongStd-Light.otf")
    # PDFNet.AddFontSubst(PDFNet.e_GB1, "AdobeMingStd-Light.otf")
    
    #Example 1) Convert the first page to PNG and TIFF at 92 DPI.
    
    # PDFDraw class is used to rasterize PDF pages.
    draw = PDFDraw()
    
    #--------------------------------------------------------------------------------
    # Example 1) Convert the first page to PNG and TIFF at 92 DPI. 
    # A three step tutorial to convert PDF page to an image.
    
    # A) Open the PDF document.
    doc = PDFDoc(input_path + "tiger.pdf")
    
    # Initialize the security handler, in case the PDF is encrypted.
    doc.InitSecurityHandler()
    
    # B) The output resolution is set to 92 DPI.
    draw.SetDPI(92)
    
    # C) Rasterize the first page in the document and save the result as PNG.
    itr = doc.GetPageIterator()
    draw.Export(itr.Current(), output_path + "tiger_92dpi.png")
    
    print("Example 1: tiger_92dpi.png")
    
    # Export the same page as TIFF
    itr = doc.GetPageIterator()
    draw.Export(itr.Current(), (output_path + "tiger_92dpi.tif"), "TIFF")
    
    #--------------------------------------------------------------------------------
    # Example 2) Convert the all pages in a given document to JPEG at 72 DPI.

    print("Example 2:")
    
    hint_set = ObjSet() # A collection of rendering 'hits'.
    
    doc = PDFDoc(input_path + "newsletter.pdf")
    # Initialize the security handler, in case the PDF is encrypted.
    doc.InitSecurityHandler()
    
    # Set the output resolution is to 72 DPI.
    draw.SetDPI(72)
    
    # Use optional encoder parameter to specify JPEG quality.
    encoder_param = hint_set.CreateDict()
    encoder_param.PutNumber("Quality", 80)
    
    # Traverse all pages in the document.
    itr = doc.GetPageIterator()
    while itr.HasNext():
        filename = "newsletter" + str(itr.Current().GetIndex()) + ".jpg"
        print(filename)
        draw.Export(itr.Current(), output_path + filename, "JPEG", encoder_param)
        itr.Next()
    print("Done.")

    # Examples 3-5
    # Common code for remaining samples.
    tiger_doc = PDFDoc(input_path + "tiger.pdf")
    # Initialize the security handler, in case the PDF is encrypted.
    tiger_doc.InitSecurityHandler()
    page = tiger_doc.GetPage(1)
    
    #--------------------------------------------------------------------------------
    # Example 3) Convert the first page to raw bitmap. Also, rotate the 
    # page 90 degrees and save the result as RAW.
    draw.SetDPI(100)    # Set the output resolution is to 100 DPI.
    draw.SetRotate(Page.e_90)   # Rotate all pages 90 degrees clockwise.
    bmp = draw.GetBitmap(page, PDFDraw.e_rgb)

    # Save the raw RGB data to disk.
    if sys.version_info.major >= 3:
	    f = open(output_path + "tiger_100dpi_rot90.raw", "w")
    else:
	    f = open(output_path + "tiger_100dpi_rot90.raw", "wb")
    try:
        f.write(str(bmp.GetBuffer()))
    finally:
        f.close()
    
    print("Example 3: tiger_100dpi_rot90.raw")
    
    draw.SetRotate(Page.e_0)    # Disable image rotation for remaining samples.
    
    #--------------------------------------------------------------------------------
    # Example 4) Convert PDF page to a fixed image size. Also illustrates some 
    # other features in PDFDraw class such as rotation, image stretching, exporting 
    # to grayscale, or monochrome.
    
    # Initialize render 'gray_hint' parameter, that is used to control the 
    # rendering process. In this case we tell the rasterizer to export the image as 
    # 1 Bit Per Component (BPC) image.
    mono_hint = hint_set.CreateDict()
    mono_hint.PutNumber("BPC", 1)
    
    # SetImageSize can be used instead of SetDPI() to adjust page scaling
    # dynamically so that given image fits into a buffer of given dimensions.
    draw.SetImageSize(1000, 1000)   # Set the output image to be 1000 wide and 1000 pixels tall
    draw.Export(page, output_path + "tiger_1000x1000.png", "PNG", mono_hint)
    print("Example 4: tiger_1000x1000.png")
    
    draw.SetImageSize(200, 400)     # Set the output image to be 200 wide and 400 pixels tall
    draw.SetRotate(Page.e_180)      # Rotate all pages 90 degrees clockwise
    
    # 'gray_hint' tells the rasterizer to export the image as grayscale.
    gray_hint = hint_set.CreateDict()
    gray_hint.PutName("ColorSpace", "Gray")
    
    draw.Export(page, (output_path + "tiger_200x400_rot180.png"), "PNG", gray_hint)
    print("Example 4: tiger_200x400_rot180.png")
    
    draw.SetImageSize(400, 200, False)  # The third parameter sets 'preserve-aspect-ratio' to False
    draw.SetRotate(Page.e_0)     # Disable image rotation
    draw.Export(page, output_path + "tiger_400x200_stretch.jpg", "JPEG")
    print("Example 4: tiger_400x200_stretch.jpg")
    
    #--------------------------------------------------------------------------------
    # Example 5) Zoom into a specific region of the page and rasterize the 
    # area at 200 DPI and as a thumbnail (i.e. a 50x50 pixel image).
    zoom_rect = Rect(216, 522, 330, 600)
    page.SetCropBox(zoom_rect)    # Set the page crop box.

    # Select the crop region to be used for drawing.
    draw.SetPageBox(Page.e_crop)
    draw.SetDPI(900)  # Set the output image resolution to 900 DPI.
    draw.Export(page, output_path + "tiger_zoom_900dpi.png", "PNG")
    print("Example 5: tiger_zoom_900dpi.png")

    # -------------------------------------------------------------------------------
    # Example 6)
    draw.SetImageSize(50, 50)      # Set the thumbnail to be 50x50 pixel image.
    draw.Export(page, output_path + "tiger_zoom_50x50.png", "PNG")
    print("Example 6: tiger_zoom_50x50.png")

    cmyk_hint = hint_set.CreateDict()
    cmyk_hint.PutName("ColorSpace", "CMYK")
    
    #--------------------------------------------------------------------------------
    # Example 7) Convert the first PDF page to CMYK TIFF at 92 DPI.
    # A three step tutorial to convert PDF page to an image
    # A) Open the PDF document
    doc = PDFDoc(input_path + "tiger.pdf")
    # Initialize the security handler, in case the PDF is encrypted.
    doc.InitSecurityHandler()
    
    # The output resolution is set to 92 DPI.
    draw.SetDPI(92)
    
    # C) Rasterize the first page in the document and save the result as TIFF.
    pg = doc.GetPage(1)
    draw.Export(pg, output_path + "out1.tif", "TIFF", cmyk_hint)
    print("Example 7: out1.tif")
        
    doc.Close()

    # A) Open the PDF document.
    doc = PDFDoc(input_path + "tiger.pdf");
    # Initialize the security handler, in case the PDF is encrypted.
    doc.InitSecurityHandler();  

    # B) Get the page matrix 
    pg = doc.GetPage(1);
    box = Page.e_crop;
    mtx = pg.GetDefaultMatrix(True, box);
    # We want to render a quadrant, so use half of width and height
    pg_w = pg.GetPageWidth(box) / 2;
    pg_h = pg.GetPageHeight(box) / 2;

    # C) Scale matrix from PDF space to buffer space
    dpi = 96.0;
    scale = dpi / 72.0; # PDF space is 72 dpi
    buf_w = int(scale * pg_w);
    buf_h = int(scale * pg_h);
    bytes_per_pixel = 4; # BGRA buffer
    buf_size = buf_w * buf_h * bytes_per_pixel;
    mtx.Translate(0, -pg_h); # translate by '-pg_h' since we want south-west quadrant
    mtx = Matrix2D(scale, 0, 0, scale, 0, 0).Multiply(mtx);

    # D) Rasterize page into memory buffer, according to our parameters
    rast = PDFRasterizer();
    buf = rast.Rasterize(pg, buf_w, buf_h, buf_w * bytes_per_pixel, bytes_per_pixel, True, mtx);

    # buf now contains raw BGRA bitmap.
    print("Example 8: Successfully rasterized into memory buffer.");

    #--------------------------------------------------------------------------------
    # Example 9) Export raster content to PNG using different image smoothing settings. 
    text_doc = PDFDoc(input_path + "lorem_ipsum.pdf");
    text_doc.InitSecurityHandler();

    draw.SetImageSmoothing(False, False);
    filename = "raster_text_no_smoothing.png";
    draw.Export(text_doc.GetPageIterator().Current(), output_path + filename);
    print("Example 9 a): " + filename + ". Done.");

    filename = "raster_text_smoothed.png";
    draw.SetImageSmoothing(True, False); # second argument = default quality bilinear resampling
    draw.Export(text_doc.GetPageIterator().Current(), output_path + filename);
    print("Example 9 b): " + filename + ". Done.");

    filename = "raster_text_high_quality.png";
    draw.SetImageSmoothing(True, True); # second argument = default quality bilinear resampling
    draw.Export(text_doc.GetPageIterator().Current(), output_path + filename);
    print("Example 9 c): " + filename + ". Done.");

    #--------------------------------------------------------------------------------
    # Example 10) Export separations directly, without conversion to an output colorspace

    separation_doc = PDFDoc(input_path + "op_blend_test.pdf");
    separation_doc.InitSecurityHandler();
    separation_hint = hint_set.CreateDict();
    separation_hint.PutName("ColorSpace", "Separation");
    draw.SetDPI(96);
    draw.SetImageSmoothing(True, True);
    draw.SetOverprint(PDFRasterizer.e_op_on);

    filename = "merged_separations.png";
    draw.Export(separation_doc.GetPageIterator().Current(), output_path + filename, "PNG");
    print("Example 10 a): " + filename + ". Done.");

    filename = "separation";
    draw.Export(separation_doc.GetPageIterator().Current(), output_path + filename, "PNG", separation_hint);
    print("Example 10 b): " + filename + "_[ink].png. Done.");

    filename = "separation_NChannel.tif";
    draw.Export(separation_doc.GetPageIterator().Current(), output_path + filename, "TIFF", separation_hint);
    print("Example 10 c): " + filename + ". Done.");

    PDFNet.Terminate()
    
if __name__ == '__main__':
    main()
```

{% 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/";

//---------------------------------------------------------------------------------------
// The following sample illustrates how to convert PDF documents to various raster image 
// formats (such as PNG, JPEG, BMP, TIFF, etc), as well as how to convert a PDF page to 
// GDI+ Bitmap for further manipulation and/or display in WinForms applications.
//---------------------------------------------------------------------------------------
	
	// The first step in every application using PDFNet is to initialize the 
	// library and set the path to common PDF resources. The library is usually 
	// initialized only once, but calling Initialize() multiple times is also fine.
	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.

	// Optional: Set ICC color profiles to fine tune color conversion 
	// for PDF 'device' color spaces...

	// PDFNet::SetResourcesPath("../../../resources");
	// PDFNet::SetColorManagement();
	// PDFNet::SetDefaultDeviceCMYKProfile("D:/Misc/ICC/USWebCoatedSWOP.icc");
	// PDFNet::SetDefaultDeviceRGBProfile("AdobeRGB1998.icc"); // will search in PDFNet resource folder.

	// ----------------------------------------------------
	// Optional: Set predefined font mappings to override default font 
	// substitution for documents with missing fonts...

	// PDFNet::AddFontSubst("StoneSans-Semibold", "C:/WINDOWS/Fonts/comic.ttf");
	// PDFNet::AddFontSubst("StoneSans", "comic.ttf");  // search for 'comic.ttf' in PDFNet resource folder.
	// PDFNet::AddFontSubst(PDFNet::e_Identity, "C:/WINDOWS/Fonts/arialuni.ttf");
	// PDFNet::AddFontSubst(PDFNet::e_Japan1, "C:/Program Files/Adobe/Acrobat 7.0/Resource/CIDFont/KozMinProVI-Regular.otf");
	// PDFNet::AddFontSubst(PDFNet::e_Japan2, "c:/myfonts/KozMinProVI-Regular.otf");
	// PDFNet::AddFontSubst(PDFNet::e_Korea1, "AdobeMyungjoStd-Medium.otf");
	// PDFNet::AddFontSubst(PDFNet::e_CNS1, "AdobeSongStd-Light.otf");
	// PDFNet::AddFontSubst(PDFNet::e_GB1, "AdobeMingStd-Light.otf");
	$draw = new PDFDraw();

	//--------------------------------------------------------------------------------
	// Example 1) Convert the first page to PNG and TIFF at 92 DPI. 
	// A three step tutorial to convert PDF page to an image.
	 
	// A) Open the PDF document.
	$doc = new PDFDoc($input_path."tiger.pdf");

	// Initialize the security handler, in case the PDF is encrypted.
	$doc->InitSecurityHandler();  

	// B) The output resolution is set to 92 DPI.
	$draw->SetDPI(92);

	// C) Rasterize the first page in the document and save the result as PNG.
	$ir = $doc->GetPageIterator();
	$draw->Export($ir->Current(), $output_path."tiger_92dpi.png");

	echo nl2br("Example 1: tiger_92dpi.png\n");

	// Export the same page as TIFF
	$draw->Export($ir->Current(), $output_path."tiger_92dpi.tif", "TIFF");

	//--------------------------------------------------------------------------------
	// Example 2) Convert the all pages in a given document to JPEG at 72 DPI.
	echo nl2br("Example 2:\n");
	$hint_set = new ObjSet(); //  A collection of rendering 'hits'.
	 
	$doc = new PDFDoc($input_path."newsletter.pdf");
	// Initialize the security handler, in case the PDF is encrypted.
	$doc->InitSecurityHandler();  

	$draw->SetDPI(72); // Set the output resolution is to 72 DPI.

	// Use optional encoder parameter to specify JPEG quality.
	$encoder_param=$hint_set->CreateDict();
	$encoder_param->PutNumber("Quality", 80);

	// Traverse all pages in the document.
	for ($itr=$doc->GetPageIterator(); $itr->HasNext(); $itr->Next()) {
		$filename = "newsletter".$itr->Current()->GetIndex().".jpg";
		echo nl2br($filename."\n");
		$draw->Export($itr->Current(), $output_path.$filename, "JPEG", $encoder_param);
	}

	echo nl2br("Done.\n");

	// Examples 3-5
				
	// Common code for remaining samples.
	$tiger_doc = new PDFDoc($input_path."tiger.pdf");
	// Initialize the security handler, in case the PDF is encrypted.
	$tiger_doc->InitSecurityHandler();  
	$page = $tiger_doc->GetPage(1);

	//--------------------------------------------------------------------------------
	// Example 3) Convert the first page to raw bitmap. Also, rotate the 
	// page 90 degrees and save the result as RAW.
	$draw->SetDPI(100); // Set the output resolution is to 100 DPI.
	$draw->SetRotate(Page::e_90);  // Rotate all pages 90 degrees clockwise.

	$bmp = $draw->GetBitmap($page, PDFDraw::e_rgb);

	// Save the raw RGB data to disk.
	file_put_contents($output_path."tiger_100dpi_rot90.raw", $bmp->GetBuffer());

	echo nl2br("Example 3: tiger_100dpi_rot90.raw\n");
	$draw->SetRotate(Page::e_0);  // Disable image rotation for remaining samples.

	//--------------------------------------------------------------------------------
	// Example 4) Convert PDF page to a fixed image size. Also illustrates some 
	// other features in PDFDraw class such as rotation, image stretching, exporting 
	// to grayscale, or monochrome.

	// Initialize render 'gray_hint' parameter, that is used to control the 
	// rendering process. In this case we tell the rasterizer to export the image as 
	// 1 Bit Per Component (BPC) image.
	$mono_hint=$hint_set->CreateDict();  
	$mono_hint->PutNumber("BPC", 1);

	// SetImageSize can be used instead of SetDPI() to adjust page  scaling 
	// dynamically so that given image fits into a buffer of given dimensions.
	$draw->SetImageSize(1000, 1000);		// Set the output image to be 1000 wide and 1000 pixels tall
	$draw->Export($page, $output_path."tiger_1000x1000.png", "PNG", $mono_hint);
	echo nl2br("Example 4: tiger_1000x1000.png\n");

	$draw->SetImageSize(200, 400);	    // Set the output image to be 200 wide and 300 pixels tall
	$draw->SetRotate(Page::e_180);  // Rotate all pages 90 degrees clockwise.

	// 'gray_hint' tells the rasterizer to export the image as grayscale.
	$gray_hint=$hint_set->CreateDict();  
	$gray_hint->PutName("ColorSpace", "Gray");

	$draw->Export($page, $output_path."tiger_200x400_rot180.png", "PNG", $gray_hint);
	echo nl2br("Example 4: tiger_200x400_rot180.png\n");

	$draw->SetImageSize(400, 200, false);  // The third parameter sets 'preserve-aspect-ratio' to false.
	$draw->SetRotate(Page::e_0);    // Disable image rotation.
	$draw->Export($page, $output_path."tiger_400x200_stretch.jpg", "JPEG");
	echo nl2br("Example 4: tiger_400x200_stretch.jpg\n");

	//--------------------------------------------------------------------------------
	// Example 5) Zoom into a specific region of the page and rasterize the 
	// area at 200 DPI and as a thumbnail (i.e. a 50x50 pixel image).
	$zoom_rect = new Rect(216.0, 522.0, 330.0, 600.0);
	$page->SetCropBox($zoom_rect);	// Set the page crop box.

	// Select the crop region to be used for drawing.
	$draw->SetPageBox(Page::e_crop); 
	$draw->SetDPI(900);  // Set the output image resolution to 900 DPI.
	$draw->Export($page, $output_path."tiger_zoom_900dpi.png", "PNG");
	echo nl2br("Example 5: tiger_zoom_900dpi.png\n");


	// -------------------------------------------------------------------------------
	// Example 6)
	$draw->SetImageSize(50, 50);	   // Set the thumbnail to be 50x50 pixel image.
	$draw->Export($page, $output_path."tiger_zoom_50x50.png", "PNG");
	echo nl2br("Example 6: tiger_zoom_50x50.png\n");

	$cmyk_hint = $hint_set->CreateDict();
	$cmyk_hint->PutName("ColorSpace", "CMYK");
	
	//--------------------------------------------------------------------------------
	// Example 7) Convert the first PDF page to CMYK TIFF at 92 DPI.
	// A three step tutorial to convert PDF page to an image
	// A) Open the PDF document.
	$doc = new PDFDoc($input_path."tiger.pdf");
	// Initialize the security handler, in case the PDF is encrypted.
	$doc->InitSecurityHandler();  

	// B) The output resolution is set to 92 DPI.
	$draw->SetDPI(92);

	// C) Rasterize the first page in the document and save the result as TIFF.
	$pg = $doc->GetPage(1);
	$draw->Export($pg, $output_path."out1.tif", "TIFF", $cmyk_hint);
	echo nl2br("Example 7: out1.tif\n");

	$doc->Close();

	//--------------------------------------------------------------------------------
	// Example 8) PDFRasterizer can be used for more complex rendering tasks, such as 
	// strip by strip or tiled document rendering. In particular, it is useful for 
	// cases where you cannot simply modify the page crop box (interactive viewing,
	// parallel rendering).  This example shows how you can rasterize the south-west
	// quadrant of a page.
	// A) Open the PDF document.
	$doc = new PDFDoc($input_path."tiger.pdf");
	// Initialize the security handler, in case the PDF is encrypted.
	$doc->InitSecurityHandler();  

	// B) Get the page matrix 
	$pg = $doc->GetPage(1);
	$box = Page::e_crop;
	$mtx = $pg->GetDefaultMatrix(true, $box);
	// We want to render a quadrant, so use half of width and height
	$pg_w = $pg->GetPageWidth($box) / 2;
	$pg_h = $pg->GetPageHeight($box) / 2;

	// C) Scale matrix from PDF space to buffer space
	$dpi = 96.0;
	$scale = $dpi / 72.0; // PDF space is 72 dpi
	$buf_w = (int)($scale * $pg_w);
	$buf_h = (int)($scale * $pg_h);
	$bytes_per_pixel = 4; // BGRA buffer
	$buf_size = $buf_w * $buf_h * $bytes_per_pixel;
	$mtx->Translate(0, -$pg_h); // translate by '-pg_h' since we want south-west quadrant
	$mtx = new Matrix2D($scale, 0.0, 0.0, $scale, 0.0, 0.0); 
	$mtx->Multiply($mtx);

	// D) Rasterize page into memory buffer, according to our parameters
	$rast = new PDFRasterizer();
	$buf = $rast->Rasterize($pg, $buf_w, $buf_h, $buf_w * $bytes_per_pixel, $bytes_per_pixel, true, $mtx);

	// buf now contains raw BGRA bitmap.
	echo nl2br("Example 8: Successfully rasterized into memory buffer.\n");

	//--------------------------------------------------------------------------------
	// Example 9) Export raster content to PNG using different image smoothing settings. 
	$text_doc = new PDFDoc($input_path."lorem_ipsum.pdf");
	$text_doc->InitSecurityHandler();

	$draw->SetImageSmoothing(false, false);
	$filename = "raster_text_no_smoothing.png";
	$ir = $text_doc->GetPageIterator();
	$draw->Export($ir->Current(), $output_path.$filename);
	echo nl2br("Example 9 a): ".$filename.". Done.\n");

	$filename = "raster_text_smoothed.png";
	$draw->SetImageSmoothing(true, false /*default quality bilinear resampling*/);
	$draw->Export($ir->Current(), $output_path.$filename);
	echo nl2br("Example 9 b): ".$filename.". Done.\n");

	$filename = "raster_text_high_quality.png";
	$draw->SetImageSmoothing(true, true /*high quality area resampling*/);
	$draw->Export($ir->Current(), $output_path.$filename);
	echo nl2br("Example 9 c): ".$filename.". Done.\n");

	//--------------------------------------------------------------------------------
	// Example 10) Export separations directly, without conversion to an output colorspace
	$separation_doc = new PDFDoc($input_path."op_blend_test.pdf");
	$separation_doc->InitSecurityHandler();
	$separation_hint = $hint_set->CreateDict();
	$separation_hint->PutName("ColorSpace", "Separation");
	$draw->SetDPI(96);
	$draw->SetImageSmoothing(true, true);
	$draw->SetOverprint(PDFRasterizer::e_op_on);

	$filename = "merged_separations.png";
	$ir = $separation_doc->GetPageIterator();
	$draw->Export($ir->Current(), $output_path.$filename, "PNG");
	echo nl2br("Example 10 a): ".$filename.". Done.\n");

	$filename = "separation";
	$draw->Export($ir->Current(), $output_path.$filename, "PNG", $separation_hint);
	echo nl2br("Example 10 b): ".$filename."_[ink].png. Done.\n");

	$filename = "separation_NChannel.tif";
	$draw->Export($ir->Current(), $output_path.$filename, "TIFF", $separation_hint);
	echo nl2br("Example 10 c): ".$filename.". Done.\n");
	PDFNet::Terminate();
?>
```

{% 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

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

#---------------------------------------------------------------------------------------
# The following sample illustrates how to convert PDF documents to various raster image 
# formats (such as PNG, JPEG, BMP, TIFF, etc), as well as how to convert a PDF page to 
# GDI+ Bitmap for further manipulation and/or display in WinForms applications.
#---------------------------------------------------------------------------------------

	# The first step in every application using PDFNet is to initialize the 
	# library and set the path to common PDF resources. The library is usually 
	# initialized only once, but calling Initialize multiple times is also fine.
	PDFNet.Initialize(PDFTronLicense.Key)
	
	# Optional: Set ICC color profiles to fine tune color conversion 
	# for PDF 'device' color spaces...

	# PDFNet.SetResourcesPath("../../../resources")
	# PDFNet.SetColorManagement
	# PDFNet.SetDefaultDeviceCMYKProfile("D:/Misc/ICC/USWebCoatedSWOP.icc")
	# PDFNet.SetDefaultDeviceRGBProfile("AdobeRGB1998.icc") # will search in PDFNet resource folder.

	# ----------------------------------------------------
	# Optional: Set predefined font mappings to override default font 
	# substitution for documents with missing fonts...

	# PDFNet.AddFontSubst("StoneSans-Semibold", "C:/WINDOWS/Fonts/comic.ttf")
	# PDFNet.AddFontSubst("StoneSans", "comic.ttf")  # search for 'comic.ttf' in PDFNet resource folder.
	# PDFNet.AddFontSubst(PDFNet.E_Identity, "C:/WINDOWS/Fonts/arialuni.ttf")
	# PDFNet.AddFontSubst(PDFNet.E_Japan1, "C:/Program Files/Adobe/Acrobat 7.0/Resource/CIDFont/KozMinProVI-Regular.otf")
	# PDFNet.AddFontSubst(PDFNet.E_Japan2, "c:/myfonts/KozMinProVI-Regular.otf")
	# PDFNet.AddFontSubst(PDFNet.E_Korea1, "AdobeMyungjoStd-Medium.otf")
	# PDFNet.AddFontSubst(PDFNet.E_CNS1, "AdobeSongStd-Light.otf")
	# PDFNet.AddFontSubst(PDFNet.E_GB1, "AdobeMingStd-Light.otf")
	
	#Example 1) Convert the first page to PNG and TIFF at 92 DPI.
	
	# PDFDraw class is used to rasterize PDF pages.
	draw = PDFDraw.new
	
	#--------------------------------------------------------------------------------
	# Example 1) Convert the first page to PNG and TIFF at 92 DPI. 
	# A three step tutorial to convert PDF page to an image.
	
	# A) Open the PDF document.
	doc = PDFDoc.new(input_path + "tiger.pdf")
	
	# Initialize the security handler, in case the PDF is encrypted.
	doc.InitSecurityHandler
	
	# B) The output resolution is set to 92 DPI.
	draw.SetDPI(92)
	
	# C) Rasterize the first page in the document and save the result as PNG.
	itr = doc.GetPageIterator
	draw.Export(itr.Current, output_path + "tiger_92dpi.png")
	
	puts "Example 1: tiger_92dpi.png"
	
	# Export the same page as TIFF
	itr = doc.GetPageIterator
	draw.Export(itr.Current, (output_path + "tiger_92dpi.tif"), "TIFF")
	
	#--------------------------------------------------------------------------------
	# Example 2) Convert the all pages in a given document to JPEG at 72 DPI.

	puts "Example 2:"
	
	hint_set = ObjSet.new # A collection of rendering 'hits'.
	
	doc = PDFDoc.new(input_path + "newsletter.pdf")
	# Initialize the security handler, in case the PDF is encrypted.
	doc.InitSecurityHandler
	
	# Set the output resolution is to 72 DPI.
	draw.SetDPI(72)
	
	# Use optional encoder parameter to specify JPEG quality.
	encoder_param = hint_set.CreateDict
	encoder_param.PutNumber("Quality", 80)
	
	# Traverse all pages in the document.
	itr = doc.GetPageIterator
	while itr.HasNext do
		filename = "newsletter" + itr.Current.GetIndex.to_s + ".jpg"
		puts filename
		draw.Export(itr.Current, output_path + filename, "JPEG", encoder_param)
		itr.Next
	end
	puts "Done."

	# Examples 3-5
	# Common code for remaining samples.
	tiger_doc = PDFDoc.new(input_path + "tiger.pdf")
	# Initialize the security handler, in case the PDF is encrypted.
	tiger_doc.InitSecurityHandler
	page = tiger_doc.GetPage(1)
	
	#--------------------------------------------------------------------------------
	# Example 3) Convert the first page to raw bitmap. Also, rotate the 
	# page 90 degrees and save the result as RAW.
	draw.SetDPI(100)	# Set the output resolution is to 100 DPI.
	draw.SetRotate(Page::E_90)   # Rotate all pages 90 degrees clockwise.
	bmp = draw.GetBitmap(page, PDFDraw::E_rgb)

	# Save the raw RGB data to disk.
	File.open(output_path + "tiger_100dpi_rot90.raw", 'w') { |file| file.write(bmp.GetBuffer) }
	
	puts "Example 3: tiger_100dpi_rot90.raw"
	
	draw.SetRotate(Page::E_0)	# Disable image rotation for remaining samples.
	
	#--------------------------------------------------------------------------------
	# Example 4) Convert PDF page to a fixed image size. Also illustrates some 
	# other features in PDFDraw class such as rotation, image stretching, exporting 
	# to grayscale, or monochrome.
	
	# Initialize render 'gray_hint' parameter, that is used to control the 
	# rendering process. In this case we tell the rasterizer to export the image as 
	# 1 Bit Per Component (BPC) image.
	mono_hint = hint_set.CreateDict
	mono_hint.PutNumber("BPC", 1)
	
	# SetImageSize can be used instead of SetDPI to adjust page scaling
	# dynamically so that given image fits into a buffer of given dimensions.
	draw.SetImageSize(1000, 1000)   # Set the output image to be 1000 wide and 1000 pixels tall
	draw.Export(page, output_path + "tiger_1000x1000.png", "PNG", mono_hint)
	puts "Example 4: tiger_1000x1000.png"
	
	draw.SetImageSize(200, 400)	 # Set the output image to be 200 wide and 400 pixels tall
	draw.SetRotate(Page::E_180)	 # Rotate all pages 90 degrees clockwise
	
	# 'gray_hint' tells the rasterizer to export the image as grayscale.
	gray_hint = hint_set.CreateDict
	gray_hint.PutName("ColorSpace", "Gray")
	
	draw.Export(page, (output_path + "tiger_200x400_rot180.png"), "PNG", gray_hint)
	puts "Example 4: tiger_200x400_rot180.png"
	
	draw.SetImageSize(400, 200, false)  # The third parameter sets 'preserve-aspect-ratio' to false
	draw.SetRotate(Page::E_0)	 # Disable image rotation
	draw.Export(page, output_path + "tiger_400x200_stretch.jpg", "JPEG")
	puts "Example 4: tiger_400x200_stretch.jpg"
	
	#--------------------------------------------------------------------------------
	# Example 5) Zoom into a specific region of the page and rasterize the 
	# area at 200 DPI and as a thumbnail (i.e. a 50x50 pixel image).
	zoom_rect = Rect.new(216, 522, 330, 600)
	page.SetCropBox(zoom_rect)	# Set the page crop box.

	# Select the crop region to be used for drawing.
	draw.SetPageBox(Page::E_crop)
	draw.SetDPI(900)  # Set the output image resolution to 900 DPI.
	draw.Export(page, output_path + "tiger_zoom_900dpi.png", "PNG")
	puts "Example 5: tiger_zoom_900dpi.png"

	# -------------------------------------------------------------------------------
	# Example 6)
	draw.SetImageSize(50, 50)	# Set the thumbnail to be 50x50 pixel image.
	draw.Export(page, output_path + "tiger_zoom_50x50.png", "PNG")
	puts "Example 6: tiger_zoom_50x50.png"

	cmyk_hint = hint_set.CreateDict
	cmyk_hint.PutName("ColorSpace", "CMYK")
	
	#--------------------------------------------------------------------------------
	# Example 6) Convert the first PDF page to CMYK TIFF at 92 DPI.
	# A three step tutorial to convert PDF page to an image
	# A) Open the PDF document
	doc = PDFDoc.new(input_path + "tiger.pdf")
	# Initialize the security handler, in case the PDF is encrypted.
	doc.InitSecurityHandler
	
	# The output resolution is set to 92 DPI.
	draw.SetDPI(92)
	
	# C) Rasterize the first page in the document and save the result as TIFF.
	pg = doc.GetPage(1)
	draw.Export(pg, output_path + "out1.tif", "TIFF", cmyk_hint)
	puts "Example 7: out1.tif"
		
	doc.Close

	# A) Open the PDF document.
	doc = PDFDoc.new(input_path + "tiger.pdf")
	# Initialize the security handler, in case the PDF is encrypted.
	doc.InitSecurityHandler  

	# B) Get the page matrix 
	pg = doc.GetPage(1)
	box = Page::E_crop
	mtx = pg.GetDefaultMatrix(true, box)
	# We want to render a quadrant, so use half of width and height
	pg_w = pg.GetPageWidth(box) / 2
	pg_h = pg.GetPageHeight(box) / 2

	# C) Scale matrix from PDF space to buffer space
	dpi = 96.0
	scale = dpi / 72.0 # PDF space is 72 dpi
	buf_w = ((scale * pg_w).floor).to_i
	buf_h = ((scale * pg_h).floor).to_i
	bytes_per_pixel = 4 # BGRA buffer
	buf_size = buf_w * buf_h * bytes_per_pixel
	mtx.Translate(0, -pg_h) # translate by '-pg_h' since we want south-west quadrant
	mtx = Matrix2D.new(scale, 0, 0, scale, 0, 0).Multiply(mtx)

	# D) Rasterize page into memory buffer, according to our parameters
	rast = PDFRasterizer.new
	buf = rast.Rasterize(pg, buf_w, buf_h, buf_w * bytes_per_pixel, bytes_per_pixel, true, mtx)

	# buf now contains raw BGRA bitmap.
	puts "Example 8: Successfully rasterized into memory buffer."

	#--------------------------------------------------------------------------------
	# Example 9) Export raster content to PNG using different image smoothing settings. 
	text_doc = PDFDoc.new(input_path + "lorem_ipsum.pdf")
	text_doc.InitSecurityHandler

	draw.SetImageSmoothing(false, false)
	filename = "raster_text_no_smoothing.png"
	draw.Export(text_doc.GetPageIterator.Current, output_path + filename)
	puts "Example 9 a): " + filename + ". Done."

	filename = "raster_text_smoothed.png"
	# default quality bilinear resampling
	draw.SetImageSmoothing(true, false)
	draw.Export(text_doc.GetPageIterator.Current, output_path + filename)
	puts "Example 9 b): " + filename + ". Done."

	filename = "raster_text_high_quality.png"
	# high quality area resampling
	draw.SetImageSmoothing(true, true)
	draw.Export(text_doc.GetPageIterator.Current, output_path + filename)
	puts "Example 9 c): " + filename + ". Done."

	#--------------------------------------------------------------------------------
	# Example 10) Export separations directly, without conversion to an output colorspace

	separation_doc = PDFDoc.new(input_path + "op_blend_test.pdf")
	separation_doc.InitSecurityHandler
	separation_hint = hint_set.CreateDict
	separation_hint.PutName("ColorSpace", "Separation")
	draw.SetDPI(96)
	draw.SetImageSmoothing(true, true)
	draw.SetOverprint(PDFRasterizer::E_op_on)

	filename = "merged_separations.png"
	draw.Export(separation_doc.GetPageIterator.Current, output_path + filename, "PNG")
	puts "Example 10 a): " + filename + ". Done."

	filename = "separation"
	draw.Export(separation_doc.GetPageIterator.Current, output_path + filename, "PNG", separation_hint)
	puts "Example 10 b): " + filename + "_[ink].png. Done."

	filename = "separation_NChannel.tif"
	draw.Export(separation_doc.GetPageIterator.Current, output_path + filename, "TIFF", separation_hint)
	puts "Example 10 c): " + filename + ". Done."
	PDFNet.Terminate
```

{% endcode %}
{% endtab %}

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

```vb
'---------------------------------------------------------------------------------------
' Copyright (c) 2001-2024 by Apryse Software Inc. All Rights Reserved.
' Consult legal.txt regarding legal and license information.     
'---------------------------------------------------------------------------------------
Imports System
Imports System.Drawing
Imports System.Drawing.Imaging
Imports System.Runtime.InteropServices

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

' <summary>
'---------------------------------------------------------------------------------------
' The following sample illustrates how to convert PDF documents to various raster image 
' formats (such as PNG, JPEG, BMP, TIFF), as well as how to convert a PDF page to GDI+ Bitmap 
' for further manipulation and/or display in WinForms applications.
'---------------------------------------------------------------------------------------
' </summary>
Module PDFDrawTestVB
    Dim pdfNetLoader As PDFNetLoader
    Sub New()
        pdfNetLoader = pdftron.PDFNetLoader.Instance()
    End Sub

    ' The main entry point for the application.
    Sub Main()

        ' The first step in every application using PDFNet is to initialize the 
        ' library and set the path to common PDF resources. The library is usually 
        ' initialized only once, but calling Initialize() multiple times is also fine.
        PDFNet.Initialize(PDFTronLicense.Key)

        ' Try
        ' Optional: Set ICC color profiles to fine tune color conversion 
        ' for PDF 'device' color spaces. You can use your own ICC profiles. 
        ' Standard Adobe color profiles can be download from Adobes site: 
        ' http://www.adobe.com/support/downloads/iccprofiles/iccprofiles_win.html
        '
        ' Simply drop all *.icc files in PDFNet resource folder or you specify 
        ' the full pathname.
        '---
        ' PDFNet.SetResourcesPath("../../../../resources")
        ' PDFNet.SetColorManagement()
        ' PDFNet.SetDefaultDeviceCMYKProfile("USWebCoatedSWOP.icc") ' will search in PDFNet resource folder.
        ' PDFNet.SetDefaultDeviceRGBProfile("AdobeRGB1998.icc") 

        ' Optional: Set predefined font mappings to override default font 
        ' substitution for documents with missing fonts. For example:
        '---
        ' PDFNet.AddFontSubst("StoneSans-Semibold", "C:/WINDOWS/Fonts/comic.ttf")
        ' PDFNet.AddFontSubst("StoneSans", "comic.ttf")  ' search for 'comic.ttf' in PDFNet resource folder.
        ' PDFNet.AddFontSubst(PDFNet.CharacterOrdering.e_Identity, "C:/WINDOWS/Fonts/arialuni.ttf")
        ' PDFNet.AddFontSubst(PDFNet.CharacterOrdering.e_Japan1, "C:/Program Files/Adobe/Acrobat 7.0/Resource/CIDFont/KozMinProVI-Regular.otf")
        ' PDFNet.AddFontSubst(PDFNet.CharacterOrdering.e_Japan2, "c:/myfonts/KozMinProVI-Regular.otf")
        '
        ' If fonts are in PDFNet resource folder, it is not necessary to specify 
        ' the full path name. For example,
        '---
        ' PDFNet.AddFontSubst(PDFNet.CharacterOrdering.e_Korea1, "AdobeMyungjoStd-Medium.otf")
        ' PDFNet.AddFontSubst(PDFNet.CharacterOrdering.e_CNS1, "AdobeSongStd-Light.otf")
        ' PDFNet.AddFontSubst(PDFNet.CharacterOrdering.e_GB1, "AdobeMingStd-Light.otf")
        ' Catch e As PDFNetException
        '   Console.WriteLine(e.Message)
        ' End Try

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

        Using draw As PDFDraw = New PDFDraw     ' PDFDraw class is used to rasterize PDF pages.

            '--------------------------------------------------------------------------------
            ' Example 1) Convert the first PDF page to PNG at 92 DPI. 
            ' A three step tutorial to convert PDF page to an image.
            Try
                ' A) Open the PDF document.
                Using doc As PDFDoc = New PDFDoc(input_path + "tiger.pdf")
                    ' Initialize the security handler, in case the PDF is encrypted.
                    doc.InitSecurityHandler()

                    ' B) The output resolution is set to 92 DPI.
                    draw.SetDPI(92)

                    ' C) Rasterize the first page in the document and save the result as PNG.
                    Dim pg As Page = doc.GetPage(1)
                    draw.Export(pg, output_path + "tiger_92dpi.png")

                    Console.WriteLine("Example 1: tiger_92dpi.png")

                    ' Export the same page as TIFF
                    draw.Export(pg, output_path + "tiger_92dpi.tif", "TIFF")
                End Using
            Catch e As PDFNetException
                Console.WriteLine(e.Message)
            End Try


            '--------------------------------------------------------------------------------
            ' Example 2) Convert the all pages in a given document to JPEG at 72 DPI.
            Console.WriteLine("Example 2:")
            Dim hint_set As ObjSet = New ObjSet    ' A collection of rendering 'hits'.
            Try
                Using doc As PDFDoc = New PDFDoc(input_path + "newsletter.pdf")
                    ' Initialize the security handler, in case the PDF is encrypted.
                    doc.InitSecurityHandler()

                    draw.SetDPI(72)              ' Set the output resolution is to 72 DPI.

                    ' Use optional encoder parameter to specify JPEG quality.
                    Dim encoder_param As SDF.Obj = hint_set.CreateDict()
                    encoder_param.PutNumber("Quality", 80)

                    ' Traverse all pages in the document.
                    Dim itr As PageIterator = doc.GetPageIterator()

                    While itr.HasNext()
                        Dim outname As String = String.Format("newsletter{0:d}.jpg", itr.GetPageNumber())
                        Console.WriteLine(outname)
                        draw.Export(itr.Current(), output_path + outname, "JPEG", encoder_param)
                        itr.Next()
                    End While

                    Console.WriteLine("Done.")
                End Using
            Catch e As PDFNetException
                Console.WriteLine(e.Message)
            End Try


            ' Examples(3 - 6)
            Try
                ' Common code for remaining samples.
                Using tiger_doc As PDFDoc = New PDFDoc(input_path + "tiger.pdf")
                    ' Initialize the security handler, in case the PDF is encrypted.
                    tiger_doc.InitSecurityHandler()
                    Dim page As Page = tiger_doc.GetPage(1)

                    '--------------------------------------------------------------------------------
                    ' Example 3) Convert the first page to GDI+ Bitmap. Also, rotate the 
                    ' page 90 degrees and save the result as TIFF.
                    draw.SetDPI(100)              ' Set the output resolution is to 100 DPI.
                    draw.SetRotate(page.Rotate.e_90)              ' Rotate all pages 90 degrees clockwise.

                    Dim bmp As System.Drawing.Bitmap = draw.GetBitmap(page)
                    ' Save the raw RGB data to disk.
                    System.IO.File.WriteAllBytes(output_path + "tiger_100dpi_rot90.raw", BitmapToByteArray(bmp))

                    Console.WriteLine("Example 3: tiger_100dpi_rot90.raw")
                    draw.SetRotate(page.Rotate.e_0)              ' Disable image rotation for remaining samples.

                    '--------------------------------------------------------------------------------
                    ' Example 4) Convert PDF page to a fixed image size. Also illustrates some 
                    ' other features in PDFDraw class such as rotation, image stretching, exporting 
                    ' to grayscale, or monochrome.

                    ' Initialize render 'gray_hint' parameter, that is used to control the 
                    ' rendering process. In this case we tell the rasterizer to export the image as 
                    ' 1 Bit Per Component (BPC) image.
                    Dim mono_hint As Obj = hint_set.CreateDict()
                    mono_hint.PutNumber("BPC", 1)

                    ' SetImageSize can be used instead of SetDPI() to adjust page  scaling 
                    ' dynamically so that given image fits into a buffer of given dimensions.
                    draw.SetImageSize(1000, 1000)            ' Set the output image to be 1000 wide and 1000 pixels tall
                    draw.Export(page, output_path + "tiger_1000x1000.png", "PNG", mono_hint)
                    Console.WriteLine("Example 4: tiger_1000x1000.png")

                    draw.SetImageSize(200, 400)            ' Set the output image to be 200 wide and 300 pixels tall
                    draw.SetRotate(page.Rotate.e_180)            ' Rotate all pages 90 degrees clockwise.

                    ' 'gray_hint' tells the rasterizer to export the image as grayscale.
                    Dim gray_hint As Obj = hint_set.CreateDict()
                    gray_hint.PutName("ColorSpace", "Gray")

                    draw.Export(page, output_path + "tiger_200x400_rot180.png", "PNG", gray_hint)
                    Console.WriteLine("Example 4: tiger_200x400_rot180.png")

                    draw.SetImageSize(400, 200, False)              ' The third parameter sets 'preserve-aspect-ratio' to false.
                    draw.SetRotate(page.Rotate.e_0)             ' Disable image rotation.
                    draw.Export(page, output_path + "tiger_400x200_stretch.jpg", "JPEG")
                    Console.WriteLine("Example 4: tiger_400x200_stretch.jpg")


                    '--------------------------------------------------------------------------------
                    ' Example 5) Zoom into a specific region of the page and rasterize the 
                    ' area at 200 DPI and as a thumbnail (i.e. a 50x50 pixel image).
                    page.SetCropBox(New Rect(216, 522, 330, 600))             ' Set the page crop box.

                    ' Select the crop region to be used for drawing.
                    draw.SetPageBox(page.Box.e_crop)
                    draw.SetDPI(900)              ' Set the output image resolution to 900 DPI.
                    draw.Export(page, output_path + "tiger_zoom_900dpi.png", "PNG")
                    Console.WriteLine("Example 5: tiger_zoom_900dpi.png")

                    draw.SetImageSize(50, 50)             ' Set the thumbnail to be 50x50 pixel image.
                    draw.Export(page, output_path + "tiger_zoom_50x50.png", "PNG")
                    Console.WriteLine("Example 6: tiger_zoom_50x50.png")
                End Using
            Catch e As PDFNetException
                Console.WriteLine(e.Message)
            End Try

            Dim cmyk_hint As Obj = hint_set.CreateDict()
            cmyk_hint.PutName("ColorSpace", "CMYK")

            '--------------------------------------------------------------------------------
            ' Example 7) Convert the first PDF page to CMYK TIFF at 92 DPI. 
            ' A three step tutorial to convert PDF page to an image.
            Try
                ' A) Open the PDF document.
                Using doc As New PDFDoc(input_path & "tiger.pdf")
                    ' Initialize the security handler, in case the PDF is encrypted.
                    doc.InitSecurityHandler()

                    ' B) The output resolution is set to 92 DPI.
                    draw.SetDPI(92)

                    ' C) Rasterize the first page in the document and save the result as TIFF.
                    Dim pg As Page = doc.GetPage(1)
                    draw.Export(pg, output_path & "out1.tif", "TIFF", cmyk_hint)
                    Console.WriteLine("Example 7: out1.tif")
                End Using
            Catch e As PDFNetException
                Console.WriteLine(e.Message)
            End Try

            '--------------------------------------------------------------------------------
            ' Example 8) PDFRasterizer can be used for more complex rendering tasks, such as 
            ' strip by strip or tiled document rendering. In particular, it is useful for 
            ' cases where you cannot simply modify the page crop box (interactive viewing,
            ' parallel rendering).  This example shows how you can rasterize the south-west
            ' quadrant of a page.
            Using rast As PDFRasterizer = New PDFRasterizer
                Try
                    ' A) Open the PDF document.
                    Using doc As PDFDoc = New PDFDoc(input_path & "tiger.pdf")
                        ' Initialize the security handler, in case the PDF is encrypted.
                        doc.InitSecurityHandler()

                        ' B) Get the page matrix 
                        Dim pg As Page = doc.GetPage(1)
                        Dim box As Page.Box = Page.Box.e_crop
                        Dim mtx As Matrix2D = pg.GetDefaultMatrix(True, box)

                        ' We want to render a quadrant, so use half of width and height
                        Dim pg_w As Double = pg.GetPageWidth(box) / 2
                        Dim pg_h As Double = pg.GetPageHeight(box) / 2

                        ' C) Scale matrix from PDF space to buffer space
                        Dim dpi As Double = 96.0
                        Dim scale As Double = dpi / 72.0 ' PDF space is 72 dpi
                        Dim buf_w As Double = Math.Floor(scale * pg_w)
                        Dim buf_h As Double = Math.Floor(scale * pg_h)
                        Dim bytes_per_pixel As Integer = 4 ' RGBA buffer
                        Dim buf_size As Double = buf_w * buf_h * bytes_per_pixel
                        mtx.Translate(0, -pg_h) ' translate by '-pg_h' since we want south-west quadrant
                        mtx = (New Matrix2D(scale, 0, 0, scale, 0, 0)) * mtx

                        ' D) Rasterize page into memory buffer, according to our parameters
                        Dim buf As Byte() = rast.Rasterize(pg, CType(buf_w, Integer), CType(buf_h, Integer), CType(buf_w * bytes_per_pixel, Integer), bytes_per_pixel, True, mtx)


                    End Using
                    Console.WriteLine("Example 8: Successfully rasterized into memory buffer.")
                Catch e As PDFNetException
                    Console.WriteLine(e.Message)
                End Try
            End Using

            '--------------------------------------------------------------------------------
            ' Example 9) Export raster content to PNG using different image smoothing settings. 
            Try
                ' A) Open the PDF document.
                Using doc As New PDFDoc(input_path & "lorem_ipsum.pdf")
                    ' Initialize the security handler, in case the PDF is encrypted.
                    doc.InitSecurityHandler()

                    ' B) The output resolution is set to 92 DPI.
                    draw.SetDPI(92)

                    ' C) Rasterize the first page in the document and save the result as TIFF.
                    Dim pg As Page = doc.GetPage(1)
                    ' Rasterize it without image smoothing
                    Dim filename As String = "raster_text_no_smoothing.png"
                    draw.SetImageSmoothing(False, False)
                    draw.Export(pg, output_path + filename)
                    Console.WriteLine("Example 9 a): " + filename + ". Done.")

                    ' Rasterize it with image smoothing
                    filename = "raster_text_smoothed.png"
                    draw.SetImageSmoothing(True, False)
                    draw.Export(pg, output_path + filename)
                    Console.WriteLine("Example 9 b): " + filename + ". Done.")

                    'rasterize it with high quality area resampling
                    filename = "raster_text_high_quality.png"
                    draw.SetImageSmoothing(True, True)
                    draw.Export(pg, output_path + filename)
                    Console.WriteLine("Example 9 c): " + filename + ". Done.")
                End Using
            Catch e As PDFNetException
                Console.WriteLine(e.Message)
            End Try

            '--------------------------------------------------------------------------------
            ' Example 10) Export separations directly, without conversion to an output colorspace 
            Try
                Using separation_doc As New PDFDoc(input_path & "op_blend_test.pdf")

                    separation_doc.InitSecurityHandler()

                    Dim separation_hint As Obj = hint_set.CreateDict()
                    separation_hint.PutName("ColorSpace", "Separation")
                    draw.SetDPI(96)
                    draw.SetImageSmoothing(True, True)
                    'set overprint preview to always on
                    draw.SetOverprint(PDFRasterizer.OverprintPreviewMode.e_op_on)

                    Dim filename As String = "merged_separations.png"
                    draw.Export(separation_doc.GetPage(1), output_path & filename, "PNG")
                    Console.WriteLine("Example 10 a): " & filename + ". Done.")

                    filename = "separation"
                    draw.Export(separation_doc.GetPage(1), output_path & filename, "PNG", separation_hint)
                    Console.WriteLine("Example 10 b): " & filename & "_[ink].png. Done.")

                    filename = "separation_NChannel.tif"
                    draw.Export(separation_doc.GetPage(1), output_path & filename, "TIFF", separation_hint)
                    Console.WriteLine("Example 10 c): " & filename & ". Done.")
                End Using

            Catch e As PDFNetException
                Console.WriteLine(e.Message)
            End Try
        End Using
        PDFNet.Terminate()
    End Sub


    Public Function BitmapToByteArray(ByVal bitmap As Bitmap) As Byte()
        Dim bmpdata As BitmapData = Nothing
        Try
            bmpdata = bitmap.LockBits(New Rectangle(0, 0, bitmap.Width, bitmap.Height), ImageLockMode.ReadOnly, bitmap.PixelFormat)
            Dim numbytes As Integer = (bmpdata.Stride * bitmap.Height)
            Dim bytedata() As Byte = New Byte((numbytes) - 1) {}
            Dim ptr As IntPtr = bmpdata.Scan0
            Marshal.Copy(ptr, bytedata, 0, numbytes)
            Return bytedata
        Finally
            If (Not (bmpdata) Is Nothing) Then
                bitmap.UnlockBits(bmpdata)
            End If

        End Try

    End Function

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/pdfdrawtest.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.
