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

# Print PDFs - PDFPrint

Sample code for using Apryse SDK to print a PDF file using the currently selected default printer. It is possible to use this printing functionality in both client and server applications without depe

Sample code for using Apryse SDK to print a PDF file using the currently selected default printer; provided in Python, C++, C#, Java, Node.js (JavaScript), PHP, Ruby, Go and VB. It is possible to use this printing functionality in both client and server applications without dependence on any third party components. Learn more about our [Server SDK](/core/get-started/get-started.md).

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

```csharp
//
// Copyright (c) 2001-2024 by Apryse Software Inc. All Rights Reserved.
//
using System;
using System.Drawing;
using System.Drawing.Printing;

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

namespace PDFPrintTestCS
{
	/// <summary>
	/// The following sample illustrates how to print PDF document using currently selected
	/// default printer. 
	/// 
	/// The first example uses the new PDF::Print::StartPrintJob function to send a rasterization 
	/// of the document with optimal compression to the printer.  If the OS is Windows 7, then the
	/// XPS print path will be used to preserve vector quality.
	/// 
	/// The second example uses PDFDraw send unoptimized rasterized data.
	/// 
	/// If you would like to rasterize page at high resolutions (e.g. more than 600 DPI), you 
	/// should use PDFRasterizer or PDFNet vector output instead of PDFDraw. 
	/// </summary>
	class PDFPrint
	{
		private static pdftron.PDFNetLoader pdfNetLoader = pdftron.PDFNetLoader.Instance();
		static PDFPrint() {}
		
		PDFDoc pdfdoc = null;
		PDFDraw pdfdraw = null;
		PageIterator pageitr = null;

		static void Main(string[] args)
		{
			var driver = new PDFPrint();
			driver.Execute(args);
		}

		void Execute(string[] args)
		{
			PDFNet.Initialize(PDFTronLicense.Key);

			// 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.
			try
			{
				// PDFNet.SetColorManagement();
				// PDFNet.SetDefaultDeviceCMYKProfile("USWebCoatedSWOP.icc"); // will search in PDFNet resource folder.
				// PDFNet.SetDefaultDeviceRGBProfile("AdobeRGB1998.icc"); 
			}
			catch (Exception)
			{
				Console.WriteLine("The specified color profile was not found.");
			}

			// 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");

			string input_path = "../../../../TestFiles/";	// Relative path to the folder containing test files.
			try
			{
				// Open the PDF document.
				Console.WriteLine("Opening the input file...");
				using (pdfdoc = new PDFDoc(input_path + "tiger.pdf"))
				{
					pdfdoc.InitSecurityHandler();


					//////////////////////////////////////////////////////////////////////////
					// Example 1: use the PDF::Print::StartPrintJob interface
					// This is silent (no progress dialog) and blocks until print job is at spooler
					// The rasterized print job is compressed before sending to printer
					Console.WriteLine("Printing the input file using PDF.Print.StartPrintJob...");

					// Setup printing options:
					PrinterMode printerMode = new PrinterMode();
					printerMode.SetAutoCenter(true);
					printerMode.SetAutoRotate(true);
					printerMode.SetCollation(true);
					printerMode.SetCopyCount(1);
					printerMode.SetDPI(300); // regardless of ordering, an explicit DPI setting overrides the OutputQuality setting
					printerMode.SetDuplexing(PrinterMode.DuplexMode.e_Duplex_Auto);
					printerMode.SetNUp(PrinterMode.NUp.e_NUp_1_1, PrinterMode.NUpPageOrder.e_PageOrder_LeftToRightThenTopToBottom);
					printerMode.SetOrientation(PrinterMode.Orientation.e_Orientation_Portrait);
					printerMode.SetOutputAnnot(PrinterMode.PrintContentTypes.e_PrintContent_DocumentAndAnnotations);

					// If the XPS print path is being used, then the printer spooler file will
					// ignore the grayscale option and be in full color
					printerMode.SetOutputColor(PrinterMode.OutputColor.e_OutputColor_Grayscale);
					printerMode.SetOutputPageBorder(false);
					printerMode.SetOutputQuality(PrinterMode.OutputQuality.e_OutputQuality_Medium);
					printerMode.SetPaperSize(new Rect(0, 0, 612, 792));
					PageSet pagesToPrint = new PageSet(1, pdfdoc.GetPageCount(), PageSet.Filter.e_all);

					// You can get the name of the default printer by using:
					// PrinterSettings ps = new PrinterSettings();
					// String printerName   ps.PrinterName();
					// however Print.StartPrintJob can also determine this for you, just pass an empty printer name	

					// Print the document on the default printer, name the print job the name of the 
					// file, print to the printer not a file, and use printer options:
					Print.StartPrintJob(pdfdoc, "", pdfdoc.GetFileName(), "", pagesToPrint, printerMode, null);


					//////////////////////////////////////////////////////////////////////////
					// Example 2: use the .Net PrintDocument class and PDFDraw rasterizer
					// This will pop up a progress dialog

					// Start printing from the first page
					pageitr = pdfdoc.GetPageIterator();
					pdfdraw = new PDFDraw();
					pdfdraw.SetPrintMode(true);
					pdfdraw.SetRasterizerType(PDFRasterizer.Type.e_BuiltIn);

					// Create a printer
					PrintDocument printer = new PrintDocument();

					// name the document to be printed
					printer.DocumentName = pdfdoc.GetFileName();

					// Set the PrintPage delegate which will be invoked to print each page
					printer.PrintPage += new PrintPageEventHandler(PrintPage);

					Console.WriteLine("Printing the input file using .NET PrintDocument and PDFDraw...");
					printer.Print();	// Start printing

					pdfdraw.Dispose();	// Free allocated resources (generally a good idea when printing many documents).
				}
			}
			catch (PDFNetException e)
			{
				Console.WriteLine(e.Message);
			}
			PDFNet.Terminate();
		}

#if NET_1_1
		// In case you need to account for 'hard margin' printer property.
		// .NET Framework 2.x or above offers direct access 'hard margin' property.
		[System.Runtime.InteropServices.DllImport("gdi32.dll")]
		private static extern int GetDeviceCaps(IntPtr hdc, int nIndex); 
		private const int PHYSICALOFFSETX = 112; 
		private const int PHYSICALOFFSETY = 113;
#endif

		// Print event hander
		void PrintPage(object sender, PrintPageEventArgs ev)
		{
			Graphics gr = ev.Graphics;

			Rectangle rectPage = ev.PageBounds;         //print without margins
			//Rectangle rectPage = ev.MarginBounds;     //print using margins

			float dpi = gr.DpiX;

			int example = 2;
			bool use_hard_margins = false;

			// Example 1) Print the Bitmap.
			if (example == 1)
			{
				pdfdraw.SetDPI(dpi);
				System.Drawing.Bitmap bmp = pdfdraw.GetBitmap(pageitr.Current());
				gr.DrawImage(bmp, rectPage, 0, 0, bmp.Width, bmp.Height, GraphicsUnit.Pixel);
			}

			// Example 2) Print via PDFDraw class.
			if (example == 2)
			{
				gr.PageUnit = GraphicsUnit.Inch;
				if (dpi > 300) dpi = 300;

				double left, right, top, bottom;

				if (use_hard_margins) // You could adjust the rectangle to account for hard and soft margins, etc.
				{
#if NET_1_1
					// This code is used to obtain printer hard margins when running on .NET 1.1x or below. 
					IntPtr hdc = new IntPtr();
					hdc = ev.Graphics.GetHdc(); // Get handle to device context.
			 
					double hardMarginX = GetDeviceCaps(hdc, PHYSICALOFFSETX);
					double hardMarginY  = GetDeviceCaps(hdc, PHYSICALOFFSETY);		
					ev.Graphics.ReleaseHdc(hdc); // Release handle to device context.
#else
					// If you are running on .NET Framework 2.x or above, you can directly access 'hard margin' property.
					double hardMarginX = ev.PageSettings.HardMarginX;
					double hardMarginY = ev.PageSettings.HardMarginY;
#endif
					left = (rectPage.Left - hardMarginX) / 100.0;
					right = (rectPage.Right - hardMarginX) / 100.0;
					top = (rectPage.Top - hardMarginY) / 100.0;
					bottom = (rectPage.Bottom - hardMarginY) / 100.0;
				}
				else
				{
					left = rectPage.Left / 100.0;
					right = rectPage.Right / 100.0;
					top = rectPage.Top / 100.0;
					bottom = rectPage.Bottom / 100.0;
				}

				// The above page dimensions are in inches. We need to convert 
				// the page dimensions to PDF units (or points). One point is 
				// 1/72 of an inch.
				pdftron.PDF.Rect rect = new Rect(left * 72, bottom * 72, right * 72, top * 72);

				try
				{
					pdfdraw.SetDPI(dpi);
					pdfdraw.DrawInRect(pageitr.Current(), gr, rect);
				}
				catch (Exception ex)
				{
					Console.WriteLine("Printing Error: " + ex.ToString());
				}
			}

			pageitr.Next();  // Move to the next page, if any
			ev.HasMorePages = pageitr.HasNext();
		}
	}
}
```

{% endcode %}
{% endtab %}

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

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

#include <PDF/PDFNet.h>
#include <PDF/PDFDoc.h>
#include <PDF/Print.h> // new Print API
#include <iostream>
#include "../../LicenseKey/CPP/LicenseKey.h"

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


/** 
 * The following sample is a simplest C/C++ program used to illustrate how to print 
 * PDF document using currently selected default printer. In this sample, PDF::Print class 
 * is used to send data to the printer. 
 * 
 * Following this function is the more complex way of using PDFDraw directly.
 *
 * The first example uses the new PDF::Print::StartPrintJob function to send a rasterization 
 * of the document with optimal compression to the printer.  If the OS is Windows 7, then the
 * XPS print path will be used to preserve vector quality.
 *  
 * The second example uses PDFDraw send unoptimized rasterized data via the print path. 
 *  
 * If you would like to rasterize page at high resolutions (e.g. more than 600 DPI), you 
 * should use PDFRasterizer or PDFNet vector output instead of PDFDraw. 
 */
int main()
{
	PDFNet::Initialize(LicenseKey);
	try
	{
		// Relative path to the folder containing test files.
		string input_path =  "../../TestFiles/";
		PDFDoc doc((input_path +  "tiger.pdf").c_str());
		doc.InitSecurityHandler();

		// Set our PrinterMode options
		PrinterMode printerMode;
		printerMode.SetCollation(true);
		printerMode.SetCopyCount(1);
		printerMode.SetDPI(600); // regardless of ordering, an explicit DPI setting overrides the OutputQuality setting
		printerMode.SetDuplexing(PrinterMode::e_Duplex_Auto);
		
		// If the XPS print path is being used, then the printer spooler file will
		// ignore the grayscale option and be in full color
		printerMode.SetOutputColor(PrinterMode::e_OutputColor_Grayscale);
		printerMode.SetOutputQuality(PrinterMode::e_OutputQuality_Medium);
		// printerMode.SetNUp(2,1);
		// printerMode.SetScaleType(PrinterMode::e_ScaleType_FitToOutputPage);

		// Print the PDF document to the default printer, using "tiger.pdf" as the document
		// name, send the file to the printer not to an output file, print all pages, set the printerMode
		// and don't provide a cancel flag.
		Print::StartPrintJob(doc, UString(""), doc.GetFileName(), UString(""), NULL, &printerMode, NULL );
	}
	catch(Common::Exception& e)
	{
		std::cout << e << std::endl;
	}
	catch(...)
	{
		std::cout << "Unknown Exception" << std::endl;
	}

	PDFNet::Terminate (); // Done with PDFNet related stuff --------------------

	return 0;
}




//////////////////////////////////////////////////////////////////////////
// The second example uses PDFDraw send unoptimized rasterized data via the print path. 
//////////////////////////////////////////////////////////////////////////
#include <PDF/PDFDraw.h> // only needed for more complex example
#if defined(_WIN32) && !defined(__WINRT__)
#include <windows.h>
#include <windef.h>
#include <wingdi.h>

// Return HDC for the default printer
HDC GetDefaultPrinterDC(void);

int PrintUsingPDFDraw ()
{	
	PRINTDLG pd;
	
	pd.lStructSize = sizeof(pd);
	pd.hDevMode = NULL;
	pd.hDevNames = NULL;
	pd.Flags = PD_USEDEVMODECOPIESANDCOLLATE | PD_RETURNDC | PD_HIDEPRINTTOFILE | PD_NOSELECTION | PD_NOPAGENUMS;
	pd.nCopies = 1;
	pd.nFromPage = 0xFFFF;
	pd.nToPage = 0xFFFF;
	pd.nMinPage = 1;
	pd.nMaxPage = 0xFFFF;
	pd.hDC = GetDefaultPrinterDC();  

	DOCINFOA docinfo;
	memset(&docinfo, 0, sizeof(DOCINFO));
	docinfo.cbSize = sizeof(docinfo);
	docinfo.lpszDocName = "My Test";
	docinfo.fwType = 0;
	docinfo.lpszDatatype = (LPSTR) 0;
	docinfo.lpszOutput = (LPSTR)0;
	
	int nError = StartDocA(pd.hDC, &docinfo);
	if(nError == SP_ERROR) {
		MessageBoxA(NULL, "Error", "Error, Printing", MB_OK | MB_ICONEXCLAMATION);
		return 1;
	}

	// Start with PDFNew related stuff -----------------------
	PDFNet::Initialize();
	try
	{
		// Relative path to the folder containing test files.
		string input_path =  "../../TestFiles/";
		PDFDoc doc((input_path +  "tiger.pdf").c_str());
		doc.InitSecurityHandler();

		PDFDraw pdfdraw;	

		pdfdraw.SetRasterizerType(PDFRasterizer::e_BuiltIn);

		//  Note: If you would like to rasterize page at high resolutions (e.g. more 
		// than 600 DPI), you should use PDFRasterizer. 
		pdfdraw.SetDPI(200); // Set DPI (Dots Per Inch).
		pdfdraw.SetPrintMode(true);

		for (PageIterator itr = doc.GetPageIterator(); itr.HasNext(); itr.Next()) 
		{
			nError = StartPage(pd.hDC);
			if(nError == SP_ERROR) {
				MessageBoxA(NULL, "Error", "Error, Printing", MB_OK | MB_ICONEXCLAMATION);
				AbortDoc(pd.hDC);
				return 1;
			} 

			// Obtain the size of printer page (in pixels).
			PDF::Rect r;
			bool use_physical_page = false;
			if (use_physical_page){
				// Use the physical page for printing. Note: the physical page is almost always 
				// greater than the printable area of the page, and never smaller. 
				r.x1 = -GetDeviceCaps(pd.hDC, PHYSICALOFFSETX);
				r.y1 = -GetDeviceCaps(pd.hDC, PHYSICALOFFSETY);
				r.x2 = GetDeviceCaps(pd.hDC, PHYSICALWIDTH) - GetDeviceCaps(pd.hDC, PHYSICALOFFSETX);
				r.y2 = GetDeviceCaps(pd.hDC, PHYSICALHEIGHT) - GetDeviceCaps(pd.hDC, PHYSICALOFFSETY);
			}
			else { // use the printable area of the page for printing.
				r.x1 = r.y1 = 0;
				r.x2 = GetDeviceCaps(pd.hDC, PHYSICALWIDTH) - GetDeviceCaps(pd.hDC, PHYSICALOFFSETX) * 2;
				r.y2 = GetDeviceCaps(pd.hDC, PHYSICALHEIGHT) - GetDeviceCaps(pd.hDC, PHYSICALOFFSETY) * 2;
			}

			// Convert page rectangle dimensions to points. One PDF point is 1/72 of an inch.
			// LOGPIXELSX/Y returns number of pixels per logical inch along the screen width/height.
			double conv_x2pts = 72.0/GetDeviceCaps(pd.hDC, LOGPIXELSX);
			double conv_y2pts = 72.0/GetDeviceCaps(pd.hDC, LOGPIXELSY);
			r.x1 *= conv_x2pts; r.y1 *= conv_y2pts;
			r.x2 *= conv_x2pts; r.y2 *= conv_y2pts;

			pdfdraw.DrawInRect(itr.Current(), pd.hDC, r);  // Print the page
			EndPage(pd.hDC);
		}
	}
	catch(Common::Exception& e)
	{
		std::cout << e << std::endl;
	}
	catch(...)
	{
		std::cout << "Unknown Exception" << std::endl;
	}

	PDFNet::Terminate (); // Done with PDFNet related stuff --------------------
	
	EndDoc(pd.hDC);
	DeleteDC(pd.hDC);
	
	return 0;
}

HDC GetDefaultPrinterDC(void) 
{ 
   char szPrinter[80]; 
   char *szDevice, *szDriver, *szOutput; 

   GetProfileStringA("WINDOWS", "DEVICE", ",,,", szPrinter, 80); 

   szDevice = strtok(szPrinter, ","); 
   szDriver = strtok(NULL, ","); 
   szOutput = strtok(NULL, ","); 

   if ( !szDevice || !szDriver || !szOutput ) 
      return 0; 
   else 
      return CreateDCA( szDriver, szDevice, szOutput, NULL ); 

	return 0;
}
#endif //_WIN32
```

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

# The following sample illustrates how to print PDF document using currently selected
# default printer. 
# 
# The first example uses the new PDF::Print::StartPrintJob function to send a rasterization 
# of the document with optimal compression to the printer.  If the OS is Windows 7, then the
# XPS print path will be used to preserve vector quality.  For earlier Windows versions
# the GDI print path will be used.  On other operating systems this will be a no-op
# 
# The second example uses PDFDraw send unoptimized rasterized data via awt.print API. 
# 
# If you would like to rasterize page at high resolutions (e.g. more than 600 DPI), you 
# should use PDFRasterizer or PDFNet vector output instead of PDFDraw.

def main():
    PDFNet.Initialize(LicenseKey)
    
    # Relative path to the folder containing the test files.
    input_path = "../../TestFiles/"
    
    doc = PDFDoc(input_path + "tiger.pdf")
    doc.InitSecurityHandler()
    
    # Set our PrinterMode options
    printerMode = PrinterMode()
    printerMode.SetCollation(True)
    printerMode.SetCopyCount(1)
    printerMode.SetDPI(100); # regardless of ordering, an explicit DPI setting overrides the OutputQuality setting
    printerMode.SetDuplexing(PrinterMode.e_Duplex_Auto)
    
    # If the XPS print path is being used, then the printer spooler file will
    # ignore the grayscale option and be in full color
    printerMode.SetOutputColor(PrinterMode.e_OutputColor_Grayscale)
    printerMode.SetOutputQuality(PrinterMode.e_OutputQuality_Medium)
    # printerMode.SetNUp(2,1)
    # printerMode.SetScaleType(PrinterMode.e_ScaleType_FitToOutPage)
    
    # Print the PDF document to the default printer, using "tiger.pdf" as the document
    # name, send the file to the printer not to an output file, print all pages, set the printerMode
    # and don't provide a cancel flag.
    Print.StartPrintJob(doc, "", doc.GetFileName(), "", None, printerMode, None)
    PDFNet.Terminate()

if __name__ == '__main__':
    main()
```

{% 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.Graphics;
import java.awt.image.BufferedImage;
import java.awt.print.PageFormat;
import java.awt.print.Printable;
import java.awt.print.PrinterException;
import java.awt.print.PrinterJob;

import javax.print.attribute.*;
import javax.print.attribute.standard.MediaPrintableArea;


import com.pdftron.common.PDFNetException;
import com.pdftron.pdf.*;

/// The following sample illustrates how to print PDF document using currently selected
/// default printer. 
/// 
/// The first example uses the new PDF::Print::StartPrintJob function to send a rasterization 
/// of the document with optimal compression to the printer.  If the OS is Windows 7, then the
/// XPS print path will be used to preserve vector quality.  For earlier Windows versions
/// the print path will be used.  On other operating systems this will be a no-op
/// 
/// The second example uses PDFDraw send unoptimized rasterized data via awt.print API. 
/// 
/// If you would like to rasterize page at high resolutions (e.g. more than 600 DPI), you 
/// should use PDFRasterizer or PDFNet vector output instead of PDFDraw. 

public class PDFPrintTest implements Printable {
    PDFDoc doc;
    PDFDraw draw;
    BufferedImage image = null;

    PDFPrintTest() {
        try {
            PDFNet.initialize(PDFTronLicense.Key());
            doc = new PDFDoc("../../TestFiles/tiger.pdf");
            doc.initSecurityHandler();

            //////////////////////////////////////////////////////////////////////////
            // Example 1: use the PDF.Print.startPrintJob interface
            // This is silent (no progress dialog) and blocks until print job is at spooler
            // The rasterized print job is compressed before sending to printer
            System.out.println("Printing the input file using PDF.Print.StartPrintJob...");

            // Print.startPrintJob can determine the default printer name for you, just pass an empty printer name

            // Setup printing options:
            PrinterMode printerMode = new PrinterMode();
            printerMode.setCollation(true);
            printerMode.setCopyCount(1);
            printerMode.setDPI(300); // regardless of ordering, an explicit DPI setting overrides the OutputQuality setting
            printerMode.setDuplexing(PrinterMode.e_Duplex_Auto);
            printerMode.setOutputColor(PrinterMode.e_OutputColor_Grayscale);
            printerMode.setOutputQuality(PrinterMode.e_OutputQuality_Medium);

            // printerMode.setPaperSize(PrinterMode.e_6_3_Quarters_Envelope);

            PageSet pagesToPrint = new PageSet(1, doc.getPageCount(), PageSet.e_all);

            // Print the document on the default printer, name the print job the name of the
            // file, print to the printer not a file, and use printer options:
            Print.startPrintJob(doc, "", "tiger.pdf", "", pagesToPrint, printerMode, null);
        } catch (PDFNetException e) {
            e.printStackTrace();
        }


        //////////////////////////////////////////////////////////////////////////
        // Example 2: Use Java.awt.print and PDFDraw rasterizer.
        System.out.println("Printing the input file using Java.awt.print API...");
        try {
            draw = new PDFDraw();
            draw.setDPI(200);

            PrinterJob job = PrinterJob.getPrinterJob();

            PageFormat pf = job.defaultPage();

            HashPrintRequestAttributeSet psettings = new HashPrintRequestAttributeSet();
            psettings.add(new MediaPrintableArea(0, 0,
                    (int) pf.getWidth(), (int) pf.getHeight(), MediaPrintableArea.MM));

            job.setPrintable(this);
            boolean ok = job.printDialog();
            if (ok) {
                try {
                    job.print(psettings);
                } catch (PrinterException ex) {
                    //The Print did not complete successfully
                    ex.printStackTrace();
                }
            }
            doc.close();
        } catch (PDFNetException e) {
            e.printStackTrace();
        }
        PDFNet.terminate();
    }

    public static void main(String[] args) {
        new PDFPrintTest();
    }

    public int print(Graphics g, PageFormat format, int page_num) throws PrinterException {
        try {
            if (page_num < 0 || page_num >= doc.getPageCount())
                return Printable.NO_SUCH_PAGE;

            draw.drawInRect(g, doc.getPage(page_num + 1), (int) (0), (int) (0),
                    (int) (format.getWidth()), (int) (format.getHeight()));

            return Printable.PAGE_EXISTS;
        } catch (PDFNetException e) {
            e.printStackTrace();
        }
        return Printable.NO_SUCH_PAGE;
    }
}
```

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

/** 
 * The following sample is a used to illustrate how to print 
 * PDF document using currently selected default printer. In this sample, PDF::Print class 
 * is used to send data to the printer. 
 * 
 * Following this function is the more complex way of using PDFDraw directly.
 *
 * The first example uses the new PDF::Print::StartPrintJob function to send a rasterization 
 * of the document with optimal compression to the printer.  If the OS is Windows 7, then the
 * XPS print path will be used to preserve vector quality.
 *  
 * The second example uses PDFDraw send unoptimized rasterized data via the GDI print path. 
 *  
 * If you would like to rasterize page at high resolutions (e.g. more than 600 DPI), you 
 * should use PDFRasterizer or PDFNet vector output instead of PDFDraw. 
 */
 
	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.
	
	// Relative path to the folder containing test files.
	$input_path = getcwd()."/../../TestFiles/";
	$doc = new PDFDoc($input_path."tiger.pdf");
	$doc->InitSecurityHandler();

	// Set our PrinterMode options
	$printerMode = new PrinterMode();
	$printerMode->SetCollation(true);
	$printerMode->SetCopyCount(1);
	$printerMode->SetDPI(600); // regardless of ordering, an explicit DPI setting overrides the OutputQuality setting
	$printerMode->SetDuplexing(PrinterMode::e_Duplex_Auto);
		
	// If the XPS print path is being used, then the printer spooler file will
	// ignore the grayscale option and be in full color
	$printerMode->SetOutputColor(PrinterMode::e_OutputColor_Grayscale);
	$printerMode->SetOutputQuality(PrinterMode::e_OutputQuality_Medium);
	// $printerMode->SetNUp(2,1);
	// $printerMode->SetScaleType(PrinterMode::e_ScaleType_FitToOutputPage);

	// Print the PDF document to the default printer, using "tiger.pdf" as the document
	// name, send the file to the printer not to an output file, print all pages, set the printerMode
	// and don't provide a cancel flag.
	PDFPrint::StartPrintJob($doc, "", $doc->GetFileName(), "", null, $printerMode, null);
	PDFNet::Terminate();
?>
```

{% endcode %}
{% endtab %}

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

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

package main
import (
	. "pdftron"
)

import  "pdftron/Samples/LicenseKey/GO"

// The following sample illustrates how to print PDF document using currently selected
// default printer. 
// 
// The first example uses the new PDF::Print::StartPrintJob function to send a rasterization 
// of the document with optimal compression to the printer.  If the OS is Windows 7, then the
// XPS print path will be used to preserve vector quality.  For earlier Windows versions
// the GDI print path will be used.  On other operating systems this will be a no-op
// 
// The second example uses PDFDraw send unoptimized rasterized data via awt.print API. 
// 
// If you would like to rasterize page at high resolutions (e.g. more than 600 DPI), you 
// should use PDFRasterizer or PDFNet vector output instead of PDFDraw.

func main(){
    PDFNetInitialize(PDFTronLicense.Key)
    
    // Relative path to the folder containing the test files.
    inputPath := "../../TestFiles/"
    
    doc := NewPDFDoc(inputPath + "tiger.pdf")
    doc.InitSecurityHandler()
    
    // Set our PrinterMode options
    printerMode := NewPrinterMode()
    printerMode.SetCollation(true)
    printerMode.SetCopyCount(1)
    printerMode.SetDPI(100); // regardless of ordering, an explicit DPI setting overrides the OutputQuality setting
    printerMode.SetDuplexing(PrinterModeE_Duplex_Auto)
    
    // If the XPS print path is being used, then the printer spooler file will
    // ignore the grayscale option and be in full color
    printerMode.SetOutputColor(PrinterModeE_OutputColor_Grayscale)
    printerMode.SetOutputQuality(PrinterModeE_OutputQuality_Medium)
    // printerMode.SetNUp(2,1)
    // printerMode.SetScaleType(PrinterModeE_ScaleType_FitToOutPage)
    
    // Print the PDF document to the default printer, using "tiger.pdf" as the document
    // name, send the file to the printer not to an output file, print all pages, set the printerMode
    // and a cancel flag to true
    pageSet := NewPageSet(1, doc.GetPageCount())
    boolValue := true
    PrintStartPrintJob(doc, "", doc.GetFileName(), "", pageSet, printerMode, &boolValue)
    PDFNetTerminate()
}
```

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

# The following sample illustrates how to print PDF document using currently selected
# default printer. 
# 
# The first example uses the new PDF::Print::StartPrintJob function to send a rasterization 
# of the document with optimal compression to the printer.  If the OS is Windows 7, then the
# XPS print path will be used to preserve vector quality.  For earlier Windows versions
# the GDI print path will be used.  On other operating systems this will be a no-op
# 
# The second example uses PDFDraw send unoptimized rasterized data via awt.print API. 
# 
# If you would like to rasterize page at high resolutions (e.g. more than 600 DPI), you 
# should use PDFRasterizer or PDFNet vector output instead of PDFDraw.

	if ENV['OS'] == 'Windows_NT' 
		PDFNet.Initialize(PDFTronLicense.Key)
	
		# Relative path to the folder containing the test files.
		input_path = "../../TestFiles/"
		
		doc = PDFDoc.new(input_path + "tiger.pdf")
		doc.InitSecurityHandler
		
		# Set our PrinterMode options
		printerMode = PrinterMode.new
		printerMode.SetCollation(true)
		printerMode.SetCopyCount(1)
		printerMode.SetDPI(100)		# regardless of ordering, an explicit DPI setting overrides the OutputQuality setting
		printerMode.SetDuplexing(PrinterMode::E_Duplex_Auto)
		
		# If the XPS print path is being used, then the printer spooler file will
		# ignore the grayscale option and be in full color
		printerMode.SetOutputColor(PrinterMode::E_OutputColor_Grayscale)
		printerMode.SetOutputQuality(PrinterMode::E_OutputQuality_Medium)
		# printerMode.SetNUp(2,1)
		# printerMode.SetScaleType(PrinterMode.e_ScaleType_FitToOutPage)
		
		# Print the PDF document to the default printer, using "tiger.pdf" as the document
		# name, send the file to the printer not to an output file, print all pages, set the printerMode
		# and don't provide a cancel flag.
		Print.StartPrintJob(doc, "", doc.GetFileName(), "", nil, printerMode, nil)
		PDFNet.Terminate
		puts "Done."
	else
		puts "This sample cannot be executed on this platform."
	end
```

{% endcode %}
{% endtab %}

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

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

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

' The following sample illustrates how to print PDF document using currently selected
' default printer. 
' 
' The first example uses the new PDF::Print::StartPrintJob function to send a rasterization 
' of the document with optimal compression to the printer.  If the OS is Windows 7, then the
' XPS print path will be used to preserve vector quality.' 
'
' The second example uses PDFDraw send unoptimized rasterized data. 
' 
' If you would like to rasterize page at high resolutions (e.g. more than 600 DPI), you 
' should use PDFRasterizer or PDFNet vector output instead of PDFDraw. 

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

        Sub Main()
            Dim driver As PDFPrint = New PDFPrint
            driver.Execute()
        End Sub
    End Module
End Namespace

Public Class PDFPrint
    Private doc As PDFDoc = Nothing
    Private pdfdraw As PDFDraw = Nothing
    Private pageitr As PageIterator = Nothing

    Sub Execute()
        PDFNet.Initialize(PDFTronLicense.Key)

        ' 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.
        '---
        ' Try
        ' 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/"
        Try
            ' Open the PDF document.
            Console.WriteLine("Opening the input file...")
            doc = New PDFDoc(input_path + "tiger.pdf")
            doc.InitSecurityHandler()

            ''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
            ' Example 1: use the PDF::Print::StartPrintJob interface
            ' This is silent (no progress dialog) and blocks until print job is at spooler
            ' The rasterized print job is compressed before sending to printer
            Console.WriteLine("Printing the input file using PDF.Print.StartPrintJob...")

            ' While you can get the name of the default printer by using:
            ' Dim ps As PrinterSettings = New PrinterSettings
            ' Dim printerName As String = ps.PrinterName()
            ' Print.StartPrintJob can also determine this for you, just pass an empty printer name

            ' To setup printing options:
            Dim printerMode As PrinterMode = New PrinterMode
            printerMode.SetCollation(True)
            printerMode.SetCopyCount(1)
            printerMode.SetDPI(300)     ' regardless of ordering, an explicit DPI setting overrides the OutputQuality setting
            printerMode.SetDuplexing(printerMode.DuplexMode.e_Duplex_Auto)
            printerMode.SetOutputColor(printerMode.OutputColor.e_OutputColor_Grayscale)
            printerMode.SetOutputQuality(printerMode.OutputQuality.e_OutputQuality_Medium)
            Dim pagesToPrint As PageSet = New PageSet(1, doc.GetPageCount(), PageSet.Filter.e_all)

            ' Print the document on the default printer, name the print job the name of the 
            ' file, print to the printer not a file, and use default printer options:
            Print.StartPrintJob(doc, "", doc.GetFileName(), "", pagesToPrint, printerMode, Nothing)


            ''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
            ' Example 2: use the .Net PrintDocument class and PDFDraw rasterizer
            ' This will pop up a progress dialog

            ' Start printing from the first page
            pageitr = doc.GetPageIterator()

            pdfdraw = New PDFDraw
            pdfdraw.SetPrintMode(True)
            pdfdraw.SetRasterizerType(PDFRasterizer.Type.e_BuiltIn)

            ' Create a printer
            Dim printer As PrintDocument = New PrintDocument

            ' Set the PrintPage delegate which will be invoked to print each page
            AddHandler printer.PrintPage, AddressOf PrintPage
            printer.Print()          ' Start printing

            pdfdraw.Dispose()            ' Free allocated resources (generally a good idea when printing many documents).
            doc.Close()           ' Close the file
        Catch e As PDFNetException
            Console.WriteLine(e.Message)
        End Try
        PDFNet.Terminate()
    End Sub

    Private Sub PrintPage(ByVal sender As Object, ByVal ev As PrintPageEventArgs)
        Dim gr As Graphics = ev.Graphics
        gr.PageUnit = GraphicsUnit.Inch
        Dim rectPage As Rectangle = ev.PageBounds

        Dim dpi As Single = gr.DpiX
        If dpi > 300 Then dpi = 300
        pdfdraw.SetDPI(dpi)

        Dim hardMarginX As Integer = 0
        Dim hardMarginY As Integer = 0
        Dim left As Double = (rectPage.Left - hardMarginX) / 100
        Dim right As Double = (rectPage.Right - hardMarginX) / 100
        Dim top As Double = (rectPage.Top - hardMarginY) / 100
        Dim bottom As Double = (rectPage.Bottom - hardMarginY) / 100
        Dim rect As pdftron.PDF.Rect = New Rect(left * 72, bottom * 72, right * 72, top * 72)

        Try
            pdfdraw.DrawInRect(pageitr.Current, gr, rect)
        Catch ex As Exception
            Console.WriteLine("Printing Error: " + ex.ToString)
        End Try

        pageitr.Next()
        ev.HasMorePages = pageitr.HasNext()
    End Sub
End Class
```

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