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.
1//
2// Copyright (c) 2001-2024 by Apryse Software Inc. All Rights Reserved.
3//
4using System;
5using System.Drawing;
6using System.Drawing.Printing;
7
8using pdftron;
9using pdftron.PDF;
10using pdftron.Common;
11using pdftron.Filters;
12
13namespace PDFPrintTestCS
14{
15	/// <summary>
16	/// The following sample illustrates how to print PDF document using currently selected
17	/// default printer. 
18	/// 
19	/// The first example uses the new PDF::Print::StartPrintJob function to send a rasterization 
20	/// of the document with optimal compression to the printer.  If the OS is Windows 7, then the
21	/// XPS print path will be used to preserve vector quality.
22	/// 
23	/// The second example uses PDFDraw send unoptimized rasterized data.
24	/// 
25	/// If you would like to rasterize page at high resolutions (e.g. more than 600 DPI), you 
26	/// should use PDFRasterizer or PDFNet vector output instead of PDFDraw. 
27	/// </summary>
28	class PDFPrint
29	{
30		private static pdftron.PDFNetLoader pdfNetLoader = pdftron.PDFNetLoader.Instance();
31		static PDFPrint() {}
32		
33		PDFDoc pdfdoc = null;
34		PDFDraw pdfdraw = null;
35		PageIterator pageitr = null;
36
37		static void Main(string[] args)
38		{
39			var driver = new PDFPrint();
40			driver.Execute(args);
41		}
42
43		void Execute(string[] args)
44		{
45			PDFNet.Initialize(PDFTronLicense.Key);
46
47			// Optional: Set ICC color profiles to fine tune color conversion 
48			// for PDF 'device' color spaces. You can use your own ICC profiles. 
49			// Standard Adobe color profiles can be download from Adobes site: 
50			// http://www.adobe.com/support/downloads/iccprofiles/iccprofiles_win.html
51			//
52			// Simply drop all *.icc files in PDFNet resource folder or you specify 
53			// the full pathname.
54			try
55			{
56				// PDFNet.SetColorManagement();
57				// PDFNet.SetDefaultDeviceCMYKProfile("USWebCoatedSWOP.icc"); // will search in PDFNet resource folder.
58				// PDFNet.SetDefaultDeviceRGBProfile("AdobeRGB1998.icc"); 
59			}
60			catch (Exception)
61			{
62				Console.WriteLine("The specified color profile was not found.");
63			}
64
65			// Optional: Set predefined font mappings to override default font 
66			// substitution for documents with missing fonts. For example:
67			//---
68			// PDFNet.AddFontSubst("StoneSans-Semibold", "C:/WINDOWS/Fonts/comic.ttf");
69			// PDFNet.AddFontSubst("StoneSans", "comic.ttf");  // search for 'comic.ttf' in PDFNet resource folder.
70			// PDFNet.AddFontSubst(PDFNet.CharacterOrdering.e_Identity, "C:/WINDOWS/Fonts/arialuni.ttf");
71			// PDFNet.AddFontSubst(PDFNet.CharacterOrdering.e_Japan1, "C:/Program Files/Adobe/Acrobat 7.0/Resource/CIDFont/KozMinProVI-Regular.otf");
72			// PDFNet.AddFontSubst(PDFNet.CharacterOrdering.e_Japan2, "c:/myfonts/KozMinProVI-Regular.otf");
73			//
74			// If fonts are in PDFNet resource folder, it is not necessary to specify 
75			// the full path name. For example,
76			//---
77			// PDFNet.AddFontSubst(PDFNet.CharacterOrdering.e_Korea1, "AdobeMyungjoStd-Medium.otf");
78			// PDFNet.AddFontSubst(PDFNet.CharacterOrdering.e_CNS1, "AdobeSongStd-Light.otf");
79			// PDFNet.AddFontSubst(PDFNet.CharacterOrdering.e_GB1, "AdobeMingStd-Light.otf");
80
81			string input_path = "../../../../TestFiles/";	// Relative path to the folder containing test files.
82			try
83			{
84				// Open the PDF document.
85				Console.WriteLine("Opening the input file...");
86				using (pdfdoc = new PDFDoc(input_path + "tiger.pdf"))
87				{
88					pdfdoc.InitSecurityHandler();
89
90
91					//////////////////////////////////////////////////////////////////////////
92					// Example 1: use the PDF::Print::StartPrintJob interface
93					// This is silent (no progress dialog) and blocks until print job is at spooler
94					// The rasterized print job is compressed before sending to printer
95					Console.WriteLine("Printing the input file using PDF.Print.StartPrintJob...");
96
97					// Setup printing options:
98					PrinterMode printerMode = new PrinterMode();
99					printerMode.SetAutoCenter(true);
100					printerMode.SetAutoRotate(true);
101					printerMode.SetCollation(true);
102					printerMode.SetCopyCount(1);
103					printerMode.SetDPI(300); // regardless of ordering, an explicit DPI setting overrides the OutputQuality setting
104					printerMode.SetDuplexing(PrinterMode.DuplexMode.e_Duplex_Auto);
105					printerMode.SetNUp(PrinterMode.NUp.e_NUp_1_1, PrinterMode.NUpPageOrder.e_PageOrder_LeftToRightThenTopToBottom);
106					printerMode.SetOrientation(PrinterMode.Orientation.e_Orientation_Portrait);
107					printerMode.SetOutputAnnot(PrinterMode.PrintContentTypes.e_PrintContent_DocumentAndAnnotations);
108
109					// If the XPS print path is being used, then the printer spooler file will
110					// ignore the grayscale option and be in full color
111					printerMode.SetOutputColor(PrinterMode.OutputColor.e_OutputColor_Grayscale);
112					printerMode.SetOutputPageBorder(false);
113					printerMode.SetOutputQuality(PrinterMode.OutputQuality.e_OutputQuality_Medium);
114					printerMode.SetPaperSize(new Rect(0, 0, 612, 792));
115					PageSet pagesToPrint = new PageSet(1, pdfdoc.GetPageCount(), PageSet.Filter.e_all);
116
117					// You can get the name of the default printer by using:
118					// PrinterSettings ps = new PrinterSettings();
119					// String printerName   ps.PrinterName();
120					// however Print.StartPrintJob can also determine this for you, just pass an empty printer name	
121
122					// Print the document on the default printer, name the print job the name of the 
123					// file, print to the printer not a file, and use printer options:
124					Print.StartPrintJob(pdfdoc, "", pdfdoc.GetFileName(), "", pagesToPrint, printerMode, null);
125
126
127					//////////////////////////////////////////////////////////////////////////
128					// Example 2: use the .Net PrintDocument class and PDFDraw rasterizer
129					// This will pop up a progress dialog
130
131					// Start printing from the first page
132					pageitr = pdfdoc.GetPageIterator();
133					pdfdraw = new PDFDraw();
134					pdfdraw.SetPrintMode(true);
135					pdfdraw.SetRasterizerType(PDFRasterizer.Type.e_BuiltIn);
136
137					// Create a printer
138					PrintDocument printer = new PrintDocument();
139
140					// name the document to be printed
141					printer.DocumentName = pdfdoc.GetFileName();
142
143					// Set the PrintPage delegate which will be invoked to print each page
144					printer.PrintPage += new PrintPageEventHandler(PrintPage);
145
146					Console.WriteLine("Printing the input file using .NET PrintDocument and PDFDraw...");
147					printer.Print();	// Start printing
148
149					pdfdraw.Dispose();	// Free allocated resources (generally a good idea when printing many documents).
150				}
151			}
152			catch (PDFNetException e)
153			{
154				Console.WriteLine(e.Message);
155			}
156			PDFNet.Terminate();
157		}
158
159#if NET_1_1
160		// In case you need to account for 'hard margin' printer property.
161		// .NET Framework 2.x or above offers direct access 'hard margin' property.
162		[System.Runtime.InteropServices.DllImport("gdi32.dll")]
163		private static extern int GetDeviceCaps(IntPtr hdc, int nIndex); 
164		private const int PHYSICALOFFSETX = 112; 
165		private const int PHYSICALOFFSETY = 113;
166#endif
167
168		// Print event hander
169		void PrintPage(object sender, PrintPageEventArgs ev)
170		{
171			Graphics gr = ev.Graphics;
172
173			Rectangle rectPage = ev.PageBounds;         //print without margins
174			//Rectangle rectPage = ev.MarginBounds;     //print using margins
175
176			float dpi = gr.DpiX;
177
178			int example = 2;
179			bool use_hard_margins = false;
180
181			// Example 1) Print the Bitmap.
182			if (example == 1)
183			{
184				pdfdraw.SetDPI(dpi);
185				System.Drawing.Bitmap bmp = pdfdraw.GetBitmap(pageitr.Current());
186				gr.DrawImage(bmp, rectPage, 0, 0, bmp.Width, bmp.Height, GraphicsUnit.Pixel);
187			}
188
189			// Example 2) Print via PDFDraw class.
190			if (example == 2)
191			{
192				gr.PageUnit = GraphicsUnit.Inch;
193				if (dpi > 300) dpi = 300;
194
195				double left, right, top, bottom;
196
197				if (use_hard_margins) // You could adjust the rectangle to account for hard and soft margins, etc.
198				{
199#if NET_1_1
200					// This code is used to obtain printer hard margins when running on .NET 1.1x or below. 
201					IntPtr hdc = new IntPtr();
202					hdc = ev.Graphics.GetHdc(); // Get handle to device context.
203			 
204					double hardMarginX = GetDeviceCaps(hdc, PHYSICALOFFSETX);
205					double hardMarginY  = GetDeviceCaps(hdc, PHYSICALOFFSETY);		
206					ev.Graphics.ReleaseHdc(hdc); // Release handle to device context.
207#else
208					// If you are running on .NET Framework 2.x or above, you can directly access 'hard margin' property.
209					double hardMarginX = ev.PageSettings.HardMarginX;
210					double hardMarginY = ev.PageSettings.HardMarginY;
211#endif
212					left = (rectPage.Left - hardMarginX) / 100.0;
213					right = (rectPage.Right - hardMarginX) / 100.0;
214					top = (rectPage.Top - hardMarginY) / 100.0;
215					bottom = (rectPage.Bottom - hardMarginY) / 100.0;
216				}
217				else
218				{
219					left = rectPage.Left / 100.0;
220					right = rectPage.Right / 100.0;
221					top = rectPage.Top / 100.0;
222					bottom = rectPage.Bottom / 100.0;
223				}
224
225				// The above page dimensions are in inches. We need to convert 
226				// the page dimensions to PDF units (or points). One point is 
227				// 1/72 of an inch.
228				pdftron.PDF.Rect rect = new Rect(left * 72, bottom * 72, right * 72, top * 72);
229
230				try
231				{
232					pdfdraw.SetDPI(dpi);
233					pdfdraw.DrawInRect(pageitr.Current(), gr, rect);
234				}
235				catch (Exception ex)
236				{
237					Console.WriteLine("Printing Error: " + ex.ToString());
238				}
239			}
240
241			pageitr.Next();  // Move to the next page, if any
242			ev.HasMorePages = pageitr.HasNext();
243		}
244	}
245}
1//---------------------------------------------------------------------------------------
2// Copyright (c) 2001-2021 by PDFTron Systems Inc. All Rights Reserved.
3// Consult legal.txt regarding legal and license information.
4//---------------------------------------------------------------------------------------
5
6#include <PDF/PDFNet.h>
7#include <PDF/PDFDoc.h>
8#include <PDF/Print.h> // new Print API
9#include <iostream>
10#include "../../LicenseKey/CPP/LicenseKey.h"
11
12using namespace std;
13using namespace pdftron;
14using namespace PDF;
15
16
17/** 
18 * The following sample is a simplest C/C++ program used to illustrate how to print 
19 * PDF document using currently selected default printer. In this sample, PDF::Print class 
20 * is used to send data to the printer. 
21 * 
22 * Following this function is the more complex way of using PDFDraw directly.
23 *
24 * The first example uses the new PDF::Print::StartPrintJob function to send a rasterization 
25 * of the document with optimal compression to the printer.  If the OS is Windows 7, then the
26 * XPS print path will be used to preserve vector quality.
27 *  
28 * The second example uses PDFDraw send unoptimized rasterized data via the print path. 
29 *  
30 * If you would like to rasterize page at high resolutions (e.g. more than 600 DPI), you 
31 * should use PDFRasterizer or PDFNet vector output instead of PDFDraw. 
32 */
33int main()
34{
35	PDFNet::Initialize(LicenseKey);
36	try
37	{
38		// Relative path to the folder containing test files.
39		string input_path =  "../../TestFiles/";
40		PDFDoc doc((input_path +  "tiger.pdf").c_str());
41		doc.InitSecurityHandler();
42
43		// Set our PrinterMode options
44		PrinterMode printerMode;
45		printerMode.SetCollation(true);
46		printerMode.SetCopyCount(1);
47		printerMode.SetDPI(600); // regardless of ordering, an explicit DPI setting overrides the OutputQuality setting
48		printerMode.SetDuplexing(PrinterMode::e_Duplex_Auto);
49		
50		// If the XPS print path is being used, then the printer spooler file will
51		// ignore the grayscale option and be in full color
52		printerMode.SetOutputColor(PrinterMode::e_OutputColor_Grayscale);
53		printerMode.SetOutputQuality(PrinterMode::e_OutputQuality_Medium);
54		// printerMode.SetNUp(2,1);
55		// printerMode.SetScaleType(PrinterMode::e_ScaleType_FitToOutputPage);
56
57		// Print the PDF document to the default printer, using "tiger.pdf" as the document
58		// name, send the file to the printer not to an output file, print all pages, set the printerMode
59		// and don't provide a cancel flag.
60		Print::StartPrintJob(doc, UString(""), doc.GetFileName(), UString(""), NULL, &printerMode, NULL );
61	}
62	catch(Common::Exception& e)
63	{
64		std::cout << e << std::endl;
65	}
66	catch(...)
67	{
68		std::cout << "Unknown Exception" << std::endl;
69	}
70
71	PDFNet::Terminate (); // Done with PDFNet related stuff --------------------
72
73	return 0;
74}
75
76
77
78
79//////////////////////////////////////////////////////////////////////////
80// The second example uses PDFDraw send unoptimized rasterized data via the print path. 
81//////////////////////////////////////////////////////////////////////////
82#include <PDF/PDFDraw.h> // only needed for more complex example
83#if defined(_WIN32) && !defined(__WINRT__)
84#include <windows.h>
85#include <windef.h>
86#include <wingdi.h>
87
88// Return HDC for the default printer
89HDC GetDefaultPrinterDC(void);
90
91int PrintUsingPDFDraw ()
92{	
93	PRINTDLG pd;
94	
95	pd.lStructSize = sizeof(pd);
96	pd.hDevMode = NULL;
97	pd.hDevNames = NULL;
98	pd.Flags = PD_USEDEVMODECOPIESANDCOLLATE | PD_RETURNDC | PD_HIDEPRINTTOFILE | PD_NOSELECTION | PD_NOPAGENUMS;
99	pd.nCopies = 1;
100	pd.nFromPage = 0xFFFF;
101	pd.nToPage = 0xFFFF;
102	pd.nMinPage = 1;
103	pd.nMaxPage = 0xFFFF;
104	pd.hDC = GetDefaultPrinterDC();  
105
106	DOCINFOA docinfo;
107	memset(&docinfo, 0, sizeof(DOCINFO));
108	docinfo.cbSize = sizeof(docinfo);
109	docinfo.lpszDocName = "My Test";
110	docinfo.fwType = 0;
111	docinfo.lpszDatatype = (LPSTR) 0;
112	docinfo.lpszOutput = (LPSTR)0;
113	
114	int nError = StartDocA(pd.hDC, &docinfo);
115	if(nError == SP_ERROR) {
116		MessageBoxA(NULL, "Error", "Error, Printing", MB_OK | MB_ICONEXCLAMATION);
117		return 1;
118	}
119
120	// Start with PDFNew related stuff -----------------------
121	PDFNet::Initialize();
122	try
123	{
124		// Relative path to the folder containing test files.
125		string input_path =  "../../TestFiles/";
126		PDFDoc doc((input_path +  "tiger.pdf").c_str());
127		doc.InitSecurityHandler();
128
129		PDFDraw pdfdraw;	
130
131		pdfdraw.SetRasterizerType(PDFRasterizer::e_BuiltIn);
132
133		//  Note: If you would like to rasterize page at high resolutions (e.g. more 
134		// than 600 DPI), you should use PDFRasterizer. 
135		pdfdraw.SetDPI(200); // Set DPI (Dots Per Inch).
136		pdfdraw.SetPrintMode(true);
137
138		for (PageIterator itr = doc.GetPageIterator(); itr.HasNext(); itr.Next()) 
139		{
140			nError = StartPage(pd.hDC);
141			if(nError == SP_ERROR) {
142				MessageBoxA(NULL, "Error", "Error, Printing", MB_OK | MB_ICONEXCLAMATION);
143				AbortDoc(pd.hDC);
144				return 1;
145			} 
146
147			// Obtain the size of printer page (in pixels).
148			PDF::Rect r;
149			bool use_physical_page = false;
150			if (use_physical_page){
151				// Use the physical page for printing. Note: the physical page is almost always 
152				// greater than the printable area of the page, and never smaller. 
153				r.x1 = -GetDeviceCaps(pd.hDC, PHYSICALOFFSETX);
154				r.y1 = -GetDeviceCaps(pd.hDC, PHYSICALOFFSETY);
155				r.x2 = GetDeviceCaps(pd.hDC, PHYSICALWIDTH) - GetDeviceCaps(pd.hDC, PHYSICALOFFSETX);
156				r.y2 = GetDeviceCaps(pd.hDC, PHYSICALHEIGHT) - GetDeviceCaps(pd.hDC, PHYSICALOFFSETY);
157			}
158			else { // use the printable area of the page for printing.
159				r.x1 = r.y1 = 0;
160				r.x2 = GetDeviceCaps(pd.hDC, PHYSICALWIDTH) - GetDeviceCaps(pd.hDC, PHYSICALOFFSETX) * 2;
161				r.y2 = GetDeviceCaps(pd.hDC, PHYSICALHEIGHT) - GetDeviceCaps(pd.hDC, PHYSICALOFFSETY) * 2;
162			}
163
164			// Convert page rectangle dimensions to points. One PDF point is 1/72 of an inch.
165			// LOGPIXELSX/Y returns number of pixels per logical inch along the screen width/height.
166			double conv_x2pts = 72.0/GetDeviceCaps(pd.hDC, LOGPIXELSX);
167			double conv_y2pts = 72.0/GetDeviceCaps(pd.hDC, LOGPIXELSY);
168			r.x1 *= conv_x2pts; r.y1 *= conv_y2pts;
169			r.x2 *= conv_x2pts; r.y2 *= conv_y2pts;
170
171			pdfdraw.DrawInRect(itr.Current(), pd.hDC, r);  // Print the page
172			EndPage(pd.hDC);
173		}
174	}
175	catch(Common::Exception& e)
176	{
177		std::cout << e << std::endl;
178	}
179	catch(...)
180	{
181		std::cout << "Unknown Exception" << std::endl;
182	}
183
184	PDFNet::Terminate (); // Done with PDFNet related stuff --------------------
185	
186	EndDoc(pd.hDC);
187	DeleteDC(pd.hDC);
188	
189	return 0;
190}
191
192HDC GetDefaultPrinterDC(void) 
193{ 
194   char szPrinter[80]; 
195   char *szDevice, *szDriver, *szOutput; 
196
197   GetProfileStringA("WINDOWS", "DEVICE", ",,,", szPrinter, 80); 
198
199   szDevice = strtok(szPrinter, ","); 
200   szDriver = strtok(NULL, ","); 
201   szOutput = strtok(NULL, ","); 
202
203   if ( !szDevice || !szDriver || !szOutput ) 
204      return 0; 
205   else 
206      return CreateDCA( szDriver, szDevice, szOutput, NULL ); 
207
208	return 0;
209}
210#endif //_WIN32
1#---------------------------------------------------------------------------------------
2# Copyright (c) 2001-2023 by Apryse Software Inc. All Rights Reserved.
3# Consult LICENSE.txt regarding license information.
4#---------------------------------------------------------------------------------------
5
6import site
7site.addsitedir("../../../PDFNetC/Lib")
8import sys
9from PDFNetPython import *
10
11sys.path.append("../../LicenseKey/PYTHON")
12from LicenseKey import *
13
14# The following sample illustrates how to print PDF document using currently selected
15# default printer. 
16# 
17# The first example uses the new PDF::Print::StartPrintJob function to send a rasterization 
18# of the document with optimal compression to the printer.  If the OS is Windows 7, then the
19# XPS print path will be used to preserve vector quality.  For earlier Windows versions
20# the GDI print path will be used.  On other operating systems this will be a no-op
21# 
22# The second example uses PDFDraw send unoptimized rasterized data via awt.print API. 
23# 
24# If you would like to rasterize page at high resolutions (e.g. more than 600 DPI), you 
25# should use PDFRasterizer or PDFNet vector output instead of PDFDraw.
26
27def main():
28    PDFNet.Initialize(LicenseKey)
29    
30    # Relative path to the folder containing the test files.
31    input_path = "../../TestFiles/"
32    
33    doc = PDFDoc(input_path + "tiger.pdf")
34    doc.InitSecurityHandler()
35    
36    # Set our PrinterMode options
37    printerMode = PrinterMode()
38    printerMode.SetCollation(True)
39    printerMode.SetCopyCount(1)
40    printerMode.SetDPI(100); # regardless of ordering, an explicit DPI setting overrides the OutputQuality setting
41    printerMode.SetDuplexing(PrinterMode.e_Duplex_Auto)
42    
43    # If the XPS print path is being used, then the printer spooler file will
44    # ignore the grayscale option and be in full color
45    printerMode.SetOutputColor(PrinterMode.e_OutputColor_Grayscale)
46    printerMode.SetOutputQuality(PrinterMode.e_OutputQuality_Medium)
47    # printerMode.SetNUp(2,1)
48    # printerMode.SetScaleType(PrinterMode.e_ScaleType_FitToOutPage)
49    
50    # Print the PDF document to the default printer, using "tiger.pdf" as the document
51    # name, send the file to the printer not to an output file, print all pages, set the printerMode
52    # and don't provide a cancel flag.
53    Print.StartPrintJob(doc, "", doc.GetFileName(), "", None, printerMode, None)
54    PDFNet.Terminate()
55
56if __name__ == '__main__':
57    main()
1//---------------------------------------------------------------------------------------
2// Copyright (c) 2001-2024 by Apryse Software Inc. All Rights Reserved.
3// Consult legal.txt regarding legal and license information.
4//---------------------------------------------------------------------------------------
5
6import java.awt.Graphics;
7import java.awt.image.BufferedImage;
8import java.awt.print.PageFormat;
9import java.awt.print.Printable;
10import java.awt.print.PrinterException;
11import java.awt.print.PrinterJob;
12
13import javax.print.attribute.*;
14import javax.print.attribute.standard.MediaPrintableArea;
15
16
17import com.pdftron.common.PDFNetException;
18import com.pdftron.pdf.*;
19
20/// The following sample illustrates how to print PDF document using currently selected
21/// default printer. 
22/// 
23/// The first example uses the new PDF::Print::StartPrintJob function to send a rasterization 
24/// of the document with optimal compression to the printer.  If the OS is Windows 7, then the
25/// XPS print path will be used to preserve vector quality.  For earlier Windows versions
26/// the print path will be used.  On other operating systems this will be a no-op
27/// 
28/// The second example uses PDFDraw send unoptimized rasterized data via awt.print API. 
29/// 
30/// If you would like to rasterize page at high resolutions (e.g. more than 600 DPI), you 
31/// should use PDFRasterizer or PDFNet vector output instead of PDFDraw. 
32
33public class PDFPrintTest implements Printable {
34    PDFDoc doc;
35    PDFDraw draw;
36    BufferedImage image = null;
37
38    PDFPrintTest() {
39        try {
40            PDFNet.initialize(PDFTronLicense.Key());
41            doc = new PDFDoc("../../TestFiles/tiger.pdf");
42            doc.initSecurityHandler();
43
44            //////////////////////////////////////////////////////////////////////////
45            // Example 1: use the PDF.Print.startPrintJob interface
46            // This is silent (no progress dialog) and blocks until print job is at spooler
47            // The rasterized print job is compressed before sending to printer
48            System.out.println("Printing the input file using PDF.Print.StartPrintJob...");
49
50            // Print.startPrintJob can determine the default printer name for you, just pass an empty printer name
51
52            // Setup printing options:
53            PrinterMode printerMode = new PrinterMode();
54            printerMode.setCollation(true);
55            printerMode.setCopyCount(1);
56            printerMode.setDPI(300); // regardless of ordering, an explicit DPI setting overrides the OutputQuality setting
57            printerMode.setDuplexing(PrinterMode.e_Duplex_Auto);
58            printerMode.setOutputColor(PrinterMode.e_OutputColor_Grayscale);
59            printerMode.setOutputQuality(PrinterMode.e_OutputQuality_Medium);
60
61            // printerMode.setPaperSize(PrinterMode.e_6_3_Quarters_Envelope);
62
63            PageSet pagesToPrint = new PageSet(1, doc.getPageCount(), PageSet.e_all);
64
65            // Print the document on the default printer, name the print job the name of the
66            // file, print to the printer not a file, and use printer options:
67            Print.startPrintJob(doc, "", "tiger.pdf", "", pagesToPrint, printerMode, null);
68        } catch (PDFNetException e) {
69            e.printStackTrace();
70        }
71
72
73        //////////////////////////////////////////////////////////////////////////
74        // Example 2: Use Java.awt.print and PDFDraw rasterizer.
75        System.out.println("Printing the input file using Java.awt.print API...");
76        try {
77            draw = new PDFDraw();
78            draw.setDPI(200);
79
80            PrinterJob job = PrinterJob.getPrinterJob();
81
82            PageFormat pf = job.defaultPage();
83
84            HashPrintRequestAttributeSet psettings = new HashPrintRequestAttributeSet();
85            psettings.add(new MediaPrintableArea(0, 0,
86                    (int) pf.getWidth(), (int) pf.getHeight(), MediaPrintableArea.MM));
87
88            job.setPrintable(this);
89            boolean ok = job.printDialog();
90            if (ok) {
91                try {
92                    job.print(psettings);
93                } catch (PrinterException ex) {
94                    //The Print did not complete successfully
95                    ex.printStackTrace();
96                }
97            }
98            doc.close();
99        } catch (PDFNetException e) {
100            e.printStackTrace();
101        }
102        PDFNet.terminate();
103    }
104
105    public static void main(String[] args) {
106        new PDFPrintTest();
107    }
108
109    public int print(Graphics g, PageFormat format, int page_num) throws PrinterException {
110        try {
111            if (page_num < 0 || page_num >= doc.getPageCount())
112                return Printable.NO_SUCH_PAGE;
113
114            draw.drawInRect(g, doc.getPage(page_num + 1), (int) (0), (int) (0),
115                    (int) (format.getWidth()), (int) (format.getHeight()));
116
117            return Printable.PAGE_EXISTS;
118        } catch (PDFNetException e) {
119            e.printStackTrace();
120        }
121        return Printable.NO_SUCH_PAGE;
122    }
123}
1<?php
2//---------------------------------------------------------------------------------------
3// Copyright (c) 2001-2023 by Apryse Software Inc. All Rights Reserved.
4// Consult LICENSE.txt regarding license information.
5//---------------------------------------------------------------------------------------
6if(file_exists("../../../PDFNetC/Lib/PDFNetPHP.php"))
7include("../../../PDFNetC/Lib/PDFNetPHP.php");
8include("../../LicenseKey/PHP/LicenseKey.php");
9
10/** 
11 * The following sample is a used to illustrate how to print 
12 * PDF document using currently selected default printer. In this sample, PDF::Print class 
13 * is used to send data to the printer. 
14 * 
15 * Following this function is the more complex way of using PDFDraw directly.
16 *
17 * The first example uses the new PDF::Print::StartPrintJob function to send a rasterization 
18 * of the document with optimal compression to the printer.  If the OS is Windows 7, then the
19 * XPS print path will be used to preserve vector quality.
20 *  
21 * The second example uses PDFDraw send unoptimized rasterized data via the GDI print path. 
22 *  
23 * If you would like to rasterize page at high resolutions (e.g. more than 600 DPI), you 
24 * should use PDFRasterizer or PDFNet vector output instead of PDFDraw. 
25 */
26 
27	PDFNet::Initialize($LicenseKey);
28	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.
29	
30	// Relative path to the folder containing test files.
31	$input_path = getcwd()."/../../TestFiles/";
32	$doc = new PDFDoc($input_path."tiger.pdf");
33	$doc->InitSecurityHandler();
34
35	// Set our PrinterMode options
36	$printerMode = new PrinterMode();
37	$printerMode->SetCollation(true);
38	$printerMode->SetCopyCount(1);
39	$printerMode->SetDPI(600); // regardless of ordering, an explicit DPI setting overrides the OutputQuality setting
40	$printerMode->SetDuplexing(PrinterMode::e_Duplex_Auto);
41		
42	// If the XPS print path is being used, then the printer spooler file will
43	// ignore the grayscale option and be in full color
44	$printerMode->SetOutputColor(PrinterMode::e_OutputColor_Grayscale);
45	$printerMode->SetOutputQuality(PrinterMode::e_OutputQuality_Medium);
46	// $printerMode->SetNUp(2,1);
47	// $printerMode->SetScaleType(PrinterMode::e_ScaleType_FitToOutputPage);
48
49	// Print the PDF document to the default printer, using "tiger.pdf" as the document
50	// name, send the file to the printer not to an output file, print all pages, set the printerMode
51	// and don't provide a cancel flag.
52	PDFPrint::StartPrintJob($doc, "", $doc->GetFileName(), "", null, $printerMode, null);
53	PDFNet::Terminate();
54?>
1//---------------------------------------------------------------------------------------
2// Copyright (c) 2001-2021 by PDFTron Systems Inc. All Rights Reserved.
3// Consult LICENSE.txt regarding license information.
4//---------------------------------------------------------------------------------------
5
6package main
7import (
8	. "pdftron"
9)
10
11import  "pdftron/Samples/LicenseKey/GO"
12
13// The following sample illustrates how to print PDF document using currently selected
14// default printer. 
15// 
16// The first example uses the new PDF::Print::StartPrintJob function to send a rasterization 
17// of the document with optimal compression to the printer.  If the OS is Windows 7, then the
18// XPS print path will be used to preserve vector quality.  For earlier Windows versions
19// the GDI print path will be used.  On other operating systems this will be a no-op
20// 
21// The second example uses PDFDraw send unoptimized rasterized data via awt.print API. 
22// 
23// If you would like to rasterize page at high resolutions (e.g. more than 600 DPI), you 
24// should use PDFRasterizer or PDFNet vector output instead of PDFDraw.
25
26func main(){
27    PDFNetInitialize(PDFTronLicense.Key)
28    
29    // Relative path to the folder containing the test files.
30    inputPath := "../../TestFiles/"
31    
32    doc := NewPDFDoc(inputPath + "tiger.pdf")
33    doc.InitSecurityHandler()
34    
35    // Set our PrinterMode options
36    printerMode := NewPrinterMode()
37    printerMode.SetCollation(true)
38    printerMode.SetCopyCount(1)
39    printerMode.SetDPI(100); // regardless of ordering, an explicit DPI setting overrides the OutputQuality setting
40    printerMode.SetDuplexing(PrinterModeE_Duplex_Auto)
41    
42    // If the XPS print path is being used, then the printer spooler file will
43    // ignore the grayscale option and be in full color
44    printerMode.SetOutputColor(PrinterModeE_OutputColor_Grayscale)
45    printerMode.SetOutputQuality(PrinterModeE_OutputQuality_Medium)
46    // printerMode.SetNUp(2,1)
47    // printerMode.SetScaleType(PrinterModeE_ScaleType_FitToOutPage)
48    
49    // Print the PDF document to the default printer, using "tiger.pdf" as the document
50    // name, send the file to the printer not to an output file, print all pages, set the printerMode
51    // and a cancel flag to true
52    pageSet := NewPageSet(1, doc.GetPageCount())
53    boolValue := true
54    PrintStartPrintJob(doc, "", doc.GetFileName(), "", pageSet, printerMode, &boolValue)
55    PDFNetTerminate()
56}
1#---------------------------------------------------------------------------------------
2# Copyright (c) 2001-2023 by Apryse Software Inc. All Rights Reserved.
3# Consult LICENSE.txt regarding license information.
4#---------------------------------------------------------------------------------------
5
6require '../../../PDFNetC/Lib/PDFNetRuby'
7include PDFNetRuby
8require '../../LicenseKey/RUBY/LicenseKey'
9
10$stdout.sync = true
11
12# The following sample illustrates how to print PDF document using currently selected
13# default printer. 
14# 
15# The first example uses the new PDF::Print::StartPrintJob function to send a rasterization 
16# of the document with optimal compression to the printer.  If the OS is Windows 7, then the
17# XPS print path will be used to preserve vector quality.  For earlier Windows versions
18# the GDI print path will be used.  On other operating systems this will be a no-op
19# 
20# The second example uses PDFDraw send unoptimized rasterized data via awt.print API. 
21# 
22# If you would like to rasterize page at high resolutions (e.g. more than 600 DPI), you 
23# should use PDFRasterizer or PDFNet vector output instead of PDFDraw.
24
25	if ENV['OS'] == 'Windows_NT' 
26		PDFNet.Initialize(PDFTronLicense.Key)
27	
28		# Relative path to the folder containing the test files.
29		input_path = "../../TestFiles/"
30		
31		doc = PDFDoc.new(input_path + "tiger.pdf")
32		doc.InitSecurityHandler
33		
34		# Set our PrinterMode options
35		printerMode = PrinterMode.new
36		printerMode.SetCollation(true)
37		printerMode.SetCopyCount(1)
38		printerMode.SetDPI(100)		# regardless of ordering, an explicit DPI setting overrides the OutputQuality setting
39		printerMode.SetDuplexing(PrinterMode::E_Duplex_Auto)
40		
41		# If the XPS print path is being used, then the printer spooler file will
42		# ignore the grayscale option and be in full color
43		printerMode.SetOutputColor(PrinterMode::E_OutputColor_Grayscale)
44		printerMode.SetOutputQuality(PrinterMode::E_OutputQuality_Medium)
45		# printerMode.SetNUp(2,1)
46		# printerMode.SetScaleType(PrinterMode.e_ScaleType_FitToOutPage)
47		
48		# Print the PDF document to the default printer, using "tiger.pdf" as the document
49		# name, send the file to the printer not to an output file, print all pages, set the printerMode
50		# and don't provide a cancel flag.
51		Print.StartPrintJob(doc, "", doc.GetFileName(), "", nil, printerMode, nil)
52		PDFNet.Terminate
53		puts "Done."
54	else
55		puts "This sample cannot be executed on this platform."
56	end
1'
2' Copyright (c) 2001-2024 by Apryse Software Inc. All Rights Reserved.
3'
4Imports System
5Imports System.Drawing
6Imports System.Drawing.Printing
7
8Imports pdftron
9Imports pdftron.Common
10Imports pdftron.Filters
11Imports pdftron.SDF
12Imports pdftron.PDF
13
14' The following sample illustrates how to print PDF document using currently selected
15' default printer. 
16' 
17' The first example uses the new PDF::Print::StartPrintJob function to send a rasterization 
18' of the document with optimal compression to the printer.  If the OS is Windows 7, then the
19' XPS print path will be used to preserve vector quality.' 
20'
21' The second example uses PDFDraw send unoptimized rasterized data. 
22' 
23' If you would like to rasterize page at high resolutions (e.g. more than 600 DPI), you 
24' should use PDFRasterizer or PDFNet vector output instead of PDFDraw. 
25
26Namespace PDFViewSimpleTestVB
27    Module PDFViewSimpleTestVB
28        Dim pdfNetLoader As PDFNetLoader
29        Sub New()
30            pdfNetLoader = pdftron.PDFNetLoader.Instance()
31        End Sub
32
33        Sub Main()
34            Dim driver As PDFPrint = New PDFPrint
35            driver.Execute()
36        End Sub
37    End Module
38End Namespace
39
40Public Class PDFPrint
41    Private doc As PDFDoc = Nothing
42    Private pdfdraw As PDFDraw = Nothing
43    Private pageitr As PageIterator = Nothing
44
45    Sub Execute()
46        PDFNet.Initialize(PDFTronLicense.Key)
47
48        ' Optional: Set ICC color profiles to fine tune color conversion 
49        ' for PDF 'device' color spaces. You can use your own ICC profiles. 
50        ' Standard Adobe color profiles can be download from Adobes site: 
51        ' http://www.adobe.com/support/downloads/iccprofiles/iccprofiles_win.html
52        '
53        ' Simply drop all *.icc files in PDFNet resource folder or you specify 
54        ' the full pathname.
55        '---
56        ' Try
57        ' PDFNet.SetColorManagement()
58        ' PDFNet.SetDefaultDeviceCMYKProfile("USWebCoatedSWOP.icc") ' will search in PDFNet resource folder.
59        ' PDFNet.SetDefaultDeviceRGBProfile("AdobeRGB1998.icc") 
60
61        ' Optional: Set predefined font mappings to override default font 
62        ' substitution for documents with missing fonts. For example:
63        '---
64        ' PDFNet.AddFontSubst("StoneSans-Semibold", "C:/WINDOWS/Fonts/comic.ttf")
65        ' PDFNet.AddFontSubst("StoneSans", "comic.ttf")  ' search for 'comic.ttf' in PDFNet resource folder.
66        ' PDFNet.AddFontSubst(PDFNet.CharacterOrdering.e_Identity, "C:/WINDOWS/Fonts/arialuni.ttf")
67        ' PDFNet.AddFontSubst(PDFNet.CharacterOrdering.e_Japan1, "C:/Program Files/Adobe/Acrobat 7.0/Resource/CIDFont/KozMinProVI-Regular.otf")
68        ' PDFNet.AddFontSubst(PDFNet.CharacterOrdering.e_Japan2, "c:/myfonts/KozMinProVI-Regular.otf")
69        '
70        ' If fonts are in PDFNet resource folder, it is not necessary to specify 
71        ' the full path name. For example,
72        '---
73        ' PDFNet.AddFontSubst(PDFNet.CharacterOrdering.e_Korea1, "AdobeMyungjoStd-Medium.otf")
74        ' PDFNet.AddFontSubst(PDFNet.CharacterOrdering.e_CNS1, "AdobeSongStd-Light.otf")
75        ' PDFNet.AddFontSubst(PDFNet.CharacterOrdering.e_GB1, "AdobeMingStd-Light.otf")
76        ' Catch e As PDFNetException
77        '   Console.WriteLine(e.Message)
78        ' End Try
79
80
81        ' Relative path to the folder containing test files.
82        Dim input_path As String = "../../../../TestFiles/"
83        Try
84            ' Open the PDF document.
85            Console.WriteLine("Opening the input file...")
86            doc = New PDFDoc(input_path + "tiger.pdf")
87            doc.InitSecurityHandler()
88
89            ''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
90            ' Example 1: use the PDF::Print::StartPrintJob interface
91            ' This is silent (no progress dialog) and blocks until print job is at spooler
92            ' The rasterized print job is compressed before sending to printer
93            Console.WriteLine("Printing the input file using PDF.Print.StartPrintJob...")
94
95            ' While you can get the name of the default printer by using:
96            ' Dim ps As PrinterSettings = New PrinterSettings
97            ' Dim printerName As String = ps.PrinterName()
98            ' Print.StartPrintJob can also determine this for you, just pass an empty printer name
99
100            ' To setup printing options:
101            Dim printerMode As PrinterMode = New PrinterMode
102            printerMode.SetCollation(True)
103            printerMode.SetCopyCount(1)
104            printerMode.SetDPI(300)     ' regardless of ordering, an explicit DPI setting overrides the OutputQuality setting
105            printerMode.SetDuplexing(printerMode.DuplexMode.e_Duplex_Auto)
106            printerMode.SetOutputColor(printerMode.OutputColor.e_OutputColor_Grayscale)
107            printerMode.SetOutputQuality(printerMode.OutputQuality.e_OutputQuality_Medium)
108            Dim pagesToPrint As PageSet = New PageSet(1, doc.GetPageCount(), PageSet.Filter.e_all)
109
110            ' Print the document on the default printer, name the print job the name of the 
111            ' file, print to the printer not a file, and use default printer options:
112            Print.StartPrintJob(doc, "", doc.GetFileName(), "", pagesToPrint, printerMode, Nothing)
113
114
115            ''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
116            ' Example 2: use the .Net PrintDocument class and PDFDraw rasterizer
117            ' This will pop up a progress dialog
118
119            ' Start printing from the first page
120            pageitr = doc.GetPageIterator()
121
122            pdfdraw = New PDFDraw
123            pdfdraw.SetPrintMode(True)
124            pdfdraw.SetRasterizerType(PDFRasterizer.Type.e_BuiltIn)
125
126            ' Create a printer
127            Dim printer As PrintDocument = New PrintDocument
128
129            ' Set the PrintPage delegate which will be invoked to print each page
130            AddHandler printer.PrintPage, AddressOf PrintPage
131            printer.Print()          ' Start printing
132
133            pdfdraw.Dispose()            ' Free allocated resources (generally a good idea when printing many documents).
134            doc.Close()           ' Close the file
135        Catch e As PDFNetException
136            Console.WriteLine(e.Message)
137        End Try
138        PDFNet.Terminate()
139    End Sub
140
141    Private Sub PrintPage(ByVal sender As Object, ByVal ev As PrintPageEventArgs)
142        Dim gr As Graphics = ev.Graphics
143        gr.PageUnit = GraphicsUnit.Inch
144        Dim rectPage As Rectangle = ev.PageBounds
145
146        Dim dpi As Single = gr.DpiX
147        If dpi > 300 Then dpi = 300
148        pdfdraw.SetDPI(dpi)
149
150        Dim hardMarginX As Integer = 0
151        Dim hardMarginY As Integer = 0
152        Dim left As Double = (rectPage.Left - hardMarginX) / 100
153        Dim right As Double = (rectPage.Right - hardMarginX) / 100
154        Dim top As Double = (rectPage.Top - hardMarginY) / 100
155        Dim bottom As Double = (rectPage.Bottom - hardMarginY) / 100
156        Dim rect As pdftron.PDF.Rect = New Rect(left * 72, bottom * 72, right * 72, top * 72)
157
158        Try
159            pdfdraw.DrawInRect(pageitr.Current, gr, rect)
160        Catch ex As Exception
161            Console.WriteLine("Printing Error: " + ex.ToString)
162        End Try
163
164        pageitr.Next()
165        ev.HasMorePages = pageitr.HasNext()
166    End Sub
167End Class
Did you find this helpful?
Trial setup questions?
Ask experts on DiscordNeed other help?
Contact SupportPricing or product questions?
Contact Sales