PDFPrint

Sample C# 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 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}

Did you find this helpful?

Trial setup questions?

Ask experts on Discord

Need other help?

Contact Support

Pricing or product questions?

Contact Sales