PDF Viewer Component - PDFView

Sample C#, VB code for using Apryse SDK's PDF viewer control to implement a number of custom tools (such as freehand tool, link creation tool, rectangular zoom etc) and custom GUI elements (such as custom navigation and printing).

For a more introductory example of how to use PDFViewCtrl, please take a look at the PDFViewSimple sample code.

Learn more about our Server SDK for .NET and PDF Viewer SDK.

1using System;
2using System.Drawing;
3using System.Drawing.Drawing2D;
4using System.Drawing.Printing;
5using System.Collections;
6using System.ComponentModel;
7using System.Windows.Forms;
8
9using pdftron;
10using pdftron.PDF;
11using pdftron.SDF;
12using pdftron.Common;
13
14namespace PDFViewCS
15{
16
17 /// <summary>
18 /// Summary description for PDFViewForm.
19 /// </summary>
20 public class PDFViewForm : System.Windows.Forms.Form
21 {
22
23 /// <summary>
24 /// Required designer variable.
25 /// </summary>
26 private System.ComponentModel.Container components = null;
27
28#if CUSTOM_NAV
29
30 // The following variables are used for custom page navigation pane...
31 private System.Windows.Forms.TabControl _pdfdoc_tab;
32 private System.Windows.Forms.TabPage _bookmarks_tab;
33 private System.Windows.Forms.TabPage _pages_tab;
34 private System.Windows.Forms.TabPage _layers_tab;
35 private System.Windows.Forms.TreeView bookmark_tree;
36 private System.Windows.Forms.TreeView layer_tree;
37 private System.Windows.Forms.Splitter splitter1;
38 private ThumbView _thumbview = null; // Custom thumbnail view.
39
40#endif
41
42 private PDFDoc _pdfdoc = null; // Currently open PDF document.
43 private MyPDFView _pdfview = null; // Main PDF view.
44 public PDFViewForm(MainForm main_form)
45 {
46 this.MdiParent = main_form;
47
48 // Create other controls created using Windows Form Designer
49 InitializeComponent();
50
51 // Create the main PDFViewCtrl control (we do it here manually for greater control)
52 _pdfview = new MyPDFView(this);
53 _pdfview.Location = new System.Drawing.Point(0, 0);
54 _pdfview.Dock = System.Windows.Forms.DockStyle.Fill;
55
56 // Optional: Set the error and current page delegates...
57 _pdfview.SetErrorReportHandler(new PDFViewErrorDelegate(ErrorMsg), null);
58 _pdfview.SetCurrentPageHandler(new PDFViewCurrentPageDelegate(UpdateStatusBar), main_form);
59 _pdfview.SetDownloadReportHandler(new PDFViewDownloadDelegate(OnDownload), null);
60 _pdfview.SetUrlExtraction(false);
61 Controls.Add(_pdfview);
62 }
63
64 public bool OpenPDF(String filename)
65 {
66 try
67 {
68 try
69 {
70 // Try to open as a PDF document...
71 _pdfdoc = new PDFDoc(filename);
72 }
73 catch (Exception ex)
74 {
75 // Try to open as a PNG, JPEG, TIF, BMP, GIF, etc.
76 _pdfdoc = OpenImage(filename);
77 if (_pdfdoc == null)
78 {
79 throw ex; // re-throw the original exception
80 }
81 }
82
83 if (!_pdfdoc.InitSecurityHandler()) // In case _pdfdoc is encrypted
84 {
85 MessageBox.Show("Document authentication error", "PDFViewCtrl Error");
86 return false;
87 }
88
89#if CUSTOM_NAV
90
91 // Populates a custom bookmark tree control with bookmark nodes (if any).
92 Bookmark root = _pdfdoc.GetFirstBookmark();
93 if (root.IsValid())
94 {
95 bookmark_tree.BeginUpdate();
96 BuildBookmarkTree(root, bookmark_tree.Nodes);
97 bookmark_tree.EndUpdate();
98 }
99
100 else
101 {
102 // Optional: Uncomment the following line to hide the bookmark
103 // tab if the document does not containing bookmarks?:
104 // _pdfdoc_tab.Hide();
105 }
106
107 // Add OCGs (if any) to 'PDF Layers' tab.
108 if (_pdfdoc.HasOC())
109 {
110 pdftron.PDF.OCG.Config cfg = _pdfdoc.GetOCGConfig();
111 Obj order = cfg.GetOrder();
112 if (order != null) {
113 layer_tree.BeginUpdate();
114 BuildLayerTree(order, cfg, layer_tree.Nodes, null);
115 layer_tree.EndUpdate();
116 }
117 }
118
119#endif
120
121 // Optional: Set page view and page presentation mode.
122 // _pdfview.SetPagePresentationMode(PDFViewCtrl.PagePresentationMode.e_single_page);
123 // _pdfview.SetPageViewMode(PDFViewCtrl.PageViewMode.e_fit_page);
124 // _pdfview.SetProgressiveRendering(false);
125
126 if (_pdfdoc.GetPageCount() > 2000)
127 {
128 // If the document has many pages use single page mode to seed up initial rendering.
129 _pdfview.SetPagePresentationMode(PDFViewCtrl.PagePresentationMode.e_single_page);
130 }
131
132 _pdfview.SetDoc(_pdfdoc);
133
134#if CUSTOM_NAV
135
136 _thumbview.SetDoc(_pdfdoc, _pdfview);
137
138#endif
139
140 SetToolMode(MyPDFView._base_tool_mode, MyPDFView._tool_mode); // Set the view to use the currently selected tool (i.e. hand, text selection, pencil, etc).
141 }
142 catch (PDFNetException ex)
143 {
144 MessageBox.Show(ex.Message);
145 return false;
146 }
147 catch (Exception ex)
148 {
149 MessageBox.Show(ex.ToString());
150 return false;
151 }
152
153 this.Text = filename; // Set the title
154
155 return true;
156 }
157
158 public bool OpenPDFUrl(String url, String password)
159 {
160 try
161 {
162 // Open a PDF file at the given url. This works best with PDF's that
163 // are linearized, as pages can be downloaded and viewed in random access order,
164 // without the need to download the entire document. A viewing session can also be
165 // persisted across multiple viewing/application sessions to remove redundant downloads
166 // and improve overall performance by using the optional cache_file parameter.
167 _pdfview.OpenURLAsync(url, "", password);
168 }
169 catch (PDFNetException ex)
170 {
171 MessageBox.Show(ex.Message);
172 return false;
173 }
174 catch (Exception ex)
175 {
176 MessageBox.Show(ex.ToString());
177 return false;
178 }
179
180 this.Text = url; // Set the title
181 return true;
182 }
183
184 /// <summary>
185 /// This callback method (delegate) was registered using _pdfview.SetDownloadReportHandler
186 /// in PDFViewCS constructor. The callback can be used to update download progress
187 /// within GUI applications etc.
188 /// </summary>
189 private void OnDownload(DownloadedType type, Int32 page_num, Int32 obj_num, String msg, Object obj)
190 {
191 switch (type)
192 {
193 case DownloadedType.e_opened:
194 // e_opened indicates that we have a valid, but incomplete PDFDoc.
195 _pdfdoc = _pdfview.GetDoc();
196 MainForm main_form = (MainForm)this.MdiParent;
197 main_form.UpdateStatusBar(_pdfview.GetCurrentPage(), _pdfview.GetDoc().GetPageCount());
198 // the PDF should be treated as read only, and only simple functions
199 // should be called on the doc, until e_finished has been called.
200 break;
201 case DownloadedType.e_page:
202 // this indicates the entire page is downloaded and it is safe to modify.
203 // for example add a new annotation
204 break;
205 case DownloadedType.e_finished:
206 // we now have the full PDF file and it can be treated like any other
207 if (MessageBox.Show("Download complete, would you like to save the PDF locally?", "PDF Downloaded", MessageBoxButtons.YesNo) == DialogResult.Yes)
208 {
209 SaveAs();
210 }
211 break;
212 case DownloadedType.e_failed:
213
214 // downloading has stopped if this occurs
215 MessageBox.Show(msg);
216 this.Text = "";
217 break;
218 }
219 }
220
221 // A utility function used to display other images types besides PDF
222 // inside MyPDFView. This functionality can be used to display TIF, JPEG,
223 // BMP, PNG, etc.
224 public PDFDoc OpenImage(string filename)
225 {
226 try
227 {
228 PDFDoc pdfDoc = new PDFDoc(); // create new document
229 ElementBuilder f = new ElementBuilder();
230 ElementWriter writer = new ElementWriter();
231 Page page = pdfDoc.PageCreate(); // Add a blank page
232 writer.Begin(page);
233
234 // Add image to the document.
235 pdftron.PDF.Image img = pdftron.PDF.Image.Create(pdfDoc, filename);
236
237 // get image rectangle
238 Rect imgBox = new Rect(0, 0, img.GetImageWidth(),
239 img.GetImageHeight());
240 Rect scaledBox = new Rect();
241 double scaleFactor;
242
243 if (imgBox.Height() / imgBox.Width() > 792 / 612)
244 {
245 scaleFactor = imgBox.Height() / 792;
246 }
247 else
248 {
249 scaleFactor = imgBox.Width() / 612;
250 }
251 scaledBox.x2 = imgBox.x2 / scaleFactor;
252 scaledBox.y2 = imgBox.y2 / scaleFactor;
253
254 // set crop and media box of this page to fit with the scaled image
255 page.SetCropBox(scaledBox);
256 page.SetMediaBox(scaledBox);
257
258 // create the image element and add it to the page
259 int width = (int)scaledBox.Width();
260 int height = (int)scaledBox.Height();
261 int offsetX = 0;
262 int offsetY = 0;
263
264 Element element = f.CreateImage(img, new Matrix2D(width, 0, 0, height, offsetX, offsetY));
265 writer.WritePlacedElement(element);
266 writer.End(); // Finish writing to the page
267 pdfDoc.PagePushBack(page);
268
269 return pdfDoc;
270 }
271 catch (Exception)
272 {
273 // MessageBox.Show(ex.ToString());
274 return null;
275 }
276 }
277
278 public Boolean IsNavSidebarVisible()
279 {
280 return _pdfview.IsNavPanelVisible();
281 }
282 public void ShowNavSidebar(Boolean show)
283 {
284 _pdfview.ShowNavPanel(show);
285 }
286 public PDFDoc GetPDFDoc()
287 {
288 if (_pdfview == null) return null;
289 else return _pdfview.GetDoc();
290 }
291 public void FitPage()
292 {
293 _pdfview.SetPageViewMode(PDFViewCtrl.PageViewMode.e_fit_page);
294 }
295
296 public void FitWidth()
297 {
298 _pdfview.SetPageViewMode(PDFViewCtrl.PageViewMode.e_fit_width);
299 }
300
301 public void ZoomIn()
302 {
303 _pdfview.SetZoom(_pdfview.GetZoom() * 2);
304 }
305
306 public void ZoomOut()
307 {
308 _pdfview.SetZoom(_pdfview.GetZoom() / 2);
309 }
310 public void FirstPage()
311 {
312 _pdfview.GotoFirstPage();
313 }
314 public void PrevPage()
315 {
316 _pdfview.GotoPreviousPage();
317 }
318
319 public void NextPage()
320 {
321 _pdfview.GotoNextPage();
322 }
323 public void LastPage()
324 {
325 _pdfview.GotoLastPage();
326 }
327
328 public void PageSingle()
329 {
330 _pdfview.SetPagePresentationMode(PDFViewCtrl.PagePresentationMode.e_single_page);
331 }
332 public void PageSingleContinuous()
333 {
334 _pdfview.SetPagePresentationMode(PDFViewCtrl.PagePresentationMode.e_single_continuous);
335 }
336 public void PageFacingContinuous()
337 {
338 _pdfview.SetPagePresentationMode(PDFViewCtrl.PagePresentationMode.e_facing_continuous);
339 }
340
341 public void PageFacing()
342 {
343 _pdfview.SetPagePresentationMode(PDFViewCtrl.PagePresentationMode.e_facing);
344 }
345
346 public void RotateClockwise()
347 {
348 _pdfview.RotateClockwise();
349 }
350
351 public void RotateCounterClockwise()
352 {
353 _pdfview.RotateCounterClockwise();
354 }
355
356 public void DocProperties()
357 {
358 _pdfview.DocProperties();
359 }
360
361 public void DeletePages()
362 {
363 _pdfview.DeletePages();
364 }
365
366 public void InsertBlankPages()
367 {
368 _pdfview.InsertBlankPages();
369 }
370
371 public void InsertPages()
372 {
373 _pdfview.InsertPages();
374 }
375
376 public void ReplacePages()
377 {
378 _pdfview.ReplacePages();
379 }
380
381 public void SetAntiAliasing(bool anti_alias)
382 {
383 _pdfview.SetAntiAliasing(anti_alias);
384 _pdfview.Update();
385 }
386 public void SetRasterizer(bool built_in)
387 {
388 if (built_in)
389 _pdfview.SetRasterizerType(PDFRasterizer.Type.e_BuiltIn);
390 else
391 _pdfview.SetRasterizerType(PDFRasterizer.Type.e_GDIPlus);
392
393 _pdfview.Update();
394 }
395
396 public void SetSmoothImages(bool smooth_images)
397 {
398 _pdfview.SetImageSmoothing(smooth_images);
399 _pdfview.Update();
400 }
401
402
403
404 public void Save(string filename)
405 {
406 if (_pdfdoc == null) return;
407
408 _pdfdoc.Lock();
409
410 try
411 {
412 // If the user created new markup, merge it before saving the document.
413 if (_pdfview != null)
414 {
415 if (_pdfview._freehand_markup != null)
416 {
417 foreach (DictionaryEntry itr in _pdfview._freehand_markup)
418 {
419 int annot_page_num = (int)itr.Key;
420 Page pg = _pdfdoc.GetPage(annot_page_num);
421
422 if (pg != null)
423 {
424 FreeHandAnnot annot = (FreeHandAnnot)itr.Value;
425 annot.DrawAnnots(pg, Pens.Red);
426 }
427 }
428
429 _pdfview._freehand_markup = null;
430 _pdfview.Invalidate();
431 _pdfview.Update();
432 }
433 }
434
435 _pdfdoc.Save(filename, pdftron.SDF.SDFDoc.SaveOptions.e_remove_unused);
436 }
437 catch (Exception ex)
438 {
439 MessageBox.Show(ex.ToString(), "Error during the Save");
440 }
441
442 _pdfdoc.Unlock();
443 }
444
445 public void SaveAs()
446 {
447 // Check if there are any annotations that need to
448 // be merged with the document.
449 if (_pdfdoc != null && _pdfview != null)
450 {
451 SaveFileDialog dlg = new SaveFileDialog();
452 dlg.Filter = "PDF Files (*.pdf)|*.pdf|All Files (*.*)|*.*";
453 dlg.DefaultExt = ".pdf";
454 dlg.FileName = Text;
455 DialogResult res = dlg.ShowDialog();
456
457 if (res == DialogResult.OK)
458 {
459 this.Save(dlg.FileName);
460 }
461 }
462 }
463
464 protected override void OnClosing(CancelEventArgs e)
465 {
466 // Check if there are any annotations that need to
467 // be merged with the document.
468 if (_pdfdoc != null && _pdfview != null && (_pdfdoc.IsModified() || _pdfview._freehand_markup != null))
469 {
470 DialogResult save = MessageBox.Show("Would you like to save the changes to the document?", "PDFViewCtrl", MessageBoxButtons.YesNoCancel);
471
472 if (save == DialogResult.Yes)
473 {
474 SaveFileDialog dlg = new SaveFileDialog();
475 dlg.Filter = "PDF Files (*.pdf)|*.pdf|All Files (*.*)|*.*";
476 dlg.DefaultExt = ".pdf";
477 dlg.FileName = Text;
478 DialogResult res = dlg.ShowDialog();
479
480 if (res == DialogResult.OK)
481 {
482 this.Save(dlg.FileName);
483 }
484 else if (res == DialogResult.Cancel)
485 {
486 e.Cancel = true;
487 }
488 }
489 else if (save == DialogResult.Cancel)
490 {
491 e.Cancel = true;
492 }
493 base.OnClosing(e);
494 }
495 }
496
497 /// <summary>
498 /// Clean up any resources being used.
499 /// </summary>
500 protected override void Dispose(bool disposing)
501 {
502 if (disposing)
503 {
504
505#if CUSTOM_NAV
506
507 _thumbview.Dispose(); // Close the thumbnail view.
508
509#endif
510
511 if (_pdfview != null)
512 {
513 _pdfview.CloseDoc();
514 _pdfview.Dispose(); // Close the open PDF document in the view.
515 }
516
517 if (_pdfdoc != null)
518 {
519 _pdfdoc.Dispose(); // Close the PDF document.
520 }
521
522 if (components != null)
523 {
524 components.Dispose();
525 }
526 }
527
528 base.Dispose(disposing);
529 }
530
531 /// <summary>
532 /// This callback method (delegate) was registered using _pdfview.SetErrorReportProc
533 /// in PDFViewCS constructor. The callback can be used to report any errors that may
534 /// occur during page rendering.
535 /// </summary>
536 public static void ErrorMsg(String message, Object obj)
537 {
538 MessageBox.Show(message, "PDFViewCtrl Error");
539 }
540
541#if CUSTOM_NAV // Custom bookmark and PDF layer navigation sample
542
543 // Handle the the bookmark select event (i.e. when the user selects a node in the bookmark tree).
544 private void BookmarkTreeAfterSelect(System.Object sender, System.Windows.Forms.TreeViewEventArgs e)
545 {
546 if (e.Node.Tag == null) return;
547
548 _pdfdoc.Lock();
549 Bookmark item = (Bookmark) e.Node.Tag;
550 Action action = item.GetAction();
551
552 if (action.IsValid()) // Handle goto actions.
553 {
554 // Other types of actions can be handled in similar way.
555 if (action.GetType() == Action.Type.e_GoTo)
556 {
557 Destination dest = action.GetDest();
558 if (dest.IsValid())
559 {
560 Page page = dest.GetPage();
561 if (page != null) _pdfview.SetCurrentPage(page.GetIndex());
562 }
563 }
564 }
565 _pdfdoc.Unlock();
566 }
567
568 // Populate the bookmark tree control with bookmark items.
569 static void BuildBookmarkTree(Bookmark item, TreeNodeCollection nodes)
570 {
571 for (int i=0; item.IsValid(); item=item.GetNext(), ++i)
572 {
573 TreeNode new_node = new TreeNode(item.GetTitle());
574 nodes.Add(new_node);
575 new_node.Tag = item;
576 if (item.IsOpen()) new_node.Expand();
577
578 if (item.HasChildren()) // Recursively add children sub-trees
579 {
580 BuildBookmarkTree(item.GetFirstChild(), new_node.Nodes);
581 }
582 }
583 }
584
585 // Handle the the layer On/OFF event
586 private void LayerTreeAfterCheck(object sender, System.Windows.Forms.TreeViewEventArgs e)
587 {
588 pdftron.PDF.OCG.Context ctx = _pdfview.GetOCGContext();
589 if (ctx == null || e.Node.Tag == null) return;
590
591 pdftron.PDF.OCG.Group ocg = (pdftron.PDF.OCG.Group) e.Node.Tag;
592 ctx.SetState(ocg, e.Node.Checked);
593 _pdfview.Update();
594 }
595
596 // Populate the layer tree control with OCG (Optional Content Group) layers.
597 static void BuildLayerTree(Obj layer_arr, pdftron.PDF.OCG.Config init_cfg, TreeNodeCollection nodes, TreeNode parent_node)
598 {
599 if (layer_arr == null || layer_arr.IsArray() == false) return;
600
601 Obj lobj;
602 int sz = layer_arr.Size();
603 for (int i=0; i<sz; ++i)
604 {
605 lobj = layer_arr.GetAt(i);
606 if (lobj.IsArray() && lobj.Size()>0)
607 {
608 TreeNode new_node = new TreeNode();
609 nodes.Add(new_node);
610 new_node.Checked = true;
611 new_node.Expand();
612
613 // Recursively add children sub-trees
614 BuildLayerTree(lobj, init_cfg, new_node.Nodes, new_node);
615
616 }
617 else if (i==0 && lobj.IsString())
618 {
619 parent_node.Text = lobj.GetAsPDFText();
620 }
621 else
622 {
623 pdftron.PDF.OCG.Group grp = new pdftron.PDF.OCG.Group(lobj);
624 if (grp.IsValid())
625 {
626 TreeNode new_node = new TreeNode(grp.GetName());
627 nodes.Add(new_node);
628 new_node.Tag = grp;
629 new_node.Checked = grp.GetInitialState(init_cfg);
630 }
631 }
632 }
633 }
634
635#endif
636
637 /// <summary>
638 /// This callback method (delegate) was registered using _pdfview.SetCurrentPageProc
639 /// in PDFViewCS constructor. The callback can be used to update the current page number
640 /// within GUI applications etc. In this case we update the status bar in the main form.
641 /// </summary>
642 public static void UpdateStatusBar(int current_page, int num_pages, Object data)
643 {
644 if (data != null)
645 {
646 MainForm main_form = (MainForm)data;
647 main_form.UpdateStatusBar(current_page, num_pages);
648 }
649 }
650
651 protected override void OnActivated(EventArgs e)
652 {
653 if (_pdfview != null && _pdfview.GetDoc() != null)
654 {
655 MainForm main_form = (MainForm)this.MdiParent;
656 main_form.UpdateStatusBar(_pdfview.GetCurrentPage(), _pdfview.GetDoc().GetPageCount());
657 }
658 }
659
660 public void SetToolMode(PDFViewCtrl.ToolMode tool_mode, MyPDFView.CustomToolMode custom_tool_mode)
661 {
662 MyPDFView._base_tool_mode = tool_mode;
663 MyPDFView._tool_mode = custom_tool_mode;
664 _pdfview.SetToolMode(tool_mode);
665 }
666
667 public void Export()
668 {
669 ExportDialog e = new ExportDialog(this._pdfdoc);
670 e.ShowDialog();
671 }
672
673 public void CopySelectedText()
674 {
675 _pdfview.OnTextCopy(null, null);
676 }
677
678 public void SelectAll()
679 {
680 _pdfview.SelectAll();
681 }
682
683 public void DeselectAll()
684 {
685 _pdfview.ClearSelection();
686 }
687
688 public void FindText()
689 {
690 _pdfview.Find(); // Use the build in Find text dialog.
691 }
692 public void Print()
693 {
694 try
695 {
696
697#if CUSTOM_PRINT
698
699 PrintDialog print_dlg = new PrintDialog();
700 print_dlg.AllowSomePages = true;
701 print_dlg.Document = _print_doc;
702 if (print_dlg.ShowDialog() == DialogResult.OK)
703 {
704 _pdfdraw = new PDFDraw();
705 _pdfdraw.SetPrintMode(true);
706 _print_doc.Print();
707 _pdfdraw.Dispose();
708 _pdfdraw = null;
709 }
710
711#else
712
713 _pdfview.Print(); // Use built in PDFPrint function.
714
715#endif
716
717 }
718 catch (Exception ex)
719 {
720 MessageBox.Show(ex.ToString());
721 }
722 }
723
724#if CUSTOM_PRINT
725
726 // In this sample, PDFDraw object is used to implement print support.
727 private PDFDraw _pdfdraw = null;
728 private PageIterator print_page_itr;
729 private System.Drawing.Printing.PrintDocument _print_doc;
730
731 private void OnBeginPDFPrint(object sender, PrintEventArgs ev)
732 {
733 PDFDoc pdfdoc = GetPDFDoc();
734 if (pdfdoc == null)
735 {
736 MessageBox.Show("Error: Print document is not selected.");
737 return;
738 }
739
740 print_page_itr = pdfdoc.GetPageIterator();
741
742 // PDFNet includes two different rasterizer implementations.
743 //
744 // The two implementations offer a trade-off between print
745 // speed and accuracy/quality, as well as a trade-off between
746 // vector and raster output.
747 //
748 // e_GDIPlus rasterizer can be used to render the page
749 // using Windows GDI+, whereas e_BuiltIn rasterizer can
750 // be used to render bitmaps using platform-independent
751 // graphics engine (in this case images are always converted
752 // to bitmap prior to printing).
753 _pdfdraw.SetRasterizerType(PDFRasterizer.Type.e_GDIPlus);
754
755 // You can uncomment the following lines in order to use
756 // built-in, platform-independent rasterizer instead of GDI+.
757 // pdfdraw.SetRasterizerType(PDFRasterizer.Type.e_BuiltIn);
758 // pdfdraw.SetDPI(200);
759 }
760
761#if NET_1_1
762
763 [System.Runtime.InteropServices.DllImport("gdi32.dll")]
764 private static extern int GetDeviceCaps(IntPtr hdc, int nIndex);
765 private const int PHYSICALOFFSETX = 112;
766 private const int PHYSICALOFFSETY = 113;
767
768#endif
769
770 private void OnPrintPDFPage(object sender, PrintPageEventArgs ev)
771 {
772 Graphics gr = ev.Graphics;
773 gr.PageUnit = GraphicsUnit.Inch;
774 bool use_hard_margins = false;
775 Rectangle rectPage = ev.PageBounds; //print without margins
776 //Rectangle rectPage = ev.MarginBounds; //print using margins
777 double left, right, top, bottom;
778
779 if (use_hard_margins) // You could adjust the rectangle to account for hard and soft margins, etc.
780 {
781
782#if NET_1_1
783
784 // This code is used to obtain printer hard margins when running on .NET 1.1x or below.
785 IntPtr hdc = new IntPtr();
786 hdc = ev.Graphics.GetHdc(); // Get handle to device context.
787 double hardMarginX = GetDeviceCaps(hdc, PHYSICALOFFSETX);
788 double hardMarginY = GetDeviceCaps(hdc, PHYSICALOFFSETY);
789 ev.Graphics.ReleaseHdc(hdc); // Release handle to device context.
790
791#else
792
793 // If you are running on .NET Framework 2.x or above, you can directly access 'hard margin' property.
794 double hardMarginX = ev.PageSettings.HardMarginX;
795 double hardMarginY = ev.PageSettings.HardMarginY;
796
797#endif
798
799 left = (rectPage.Left - hardMarginX) / 100.0;
800 right = (rectPage.Right - hardMarginX) / 100.0;
801 top = (rectPage.Top - hardMarginY) / 100.0;
802 bottom = (rectPage.Bottom - hardMarginY) / 100.0;
803 }
804 else
805 {
806
807 left= rectPage.Left / 100.0;
808 right = rectPage.Right / 100.0;
809 top = rectPage.Top / 100.0;
810 bottom= rectPage.Bottom / 100.0;
811 }
812
813 // The above page dimensions are in inches. We need to convert
814 // the page dimensions to PDF units (or points). One point is
815 // 1/72 of an inch.
816 pdftron.PDF.Rect rect = new Rect(left*72, bottom*72, right*72, top*72);
817
818 PDFDoc pdfdoc = GetPDFDoc();
819 if (pdfdoc == null)
820 {
821 MessageBox.Show("Error: Print document is not selected.");
822 return;
823 }
824 pdfdoc.Lock();
825
826 try
827 {
828 if (print_page_itr.HasNext())
829 {
830 _pdfdraw.DrawInRect(print_page_itr.Current(), gr, rect);
831
832 // Move to the next page, or finish printing
833 print_page_itr.Next();
834 ev.HasMorePages = print_page_itr.HasNext();
835 }
836 else ev.HasMorePages = false;
837 }
838 catch (Exception ex)
839 {
840 MessageBox.Show("Printing Error: " + ex.ToString());
841 }
842 pdfdoc.Unlock();
843 }
844
845#endif
846
847 private void InitializeComponent()
848 {
849 System.Resources.ResourceManager resources = new System.Resources.ResourceManager(typeof(PDFViewForm));
850
851 //
852 // PDFViewForm
853 //
854 this.BackColor = System.Drawing.SystemColors.Control;
855 this.Cursor = System.Windows.Forms.Cursors.Hand;
856 this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
857 this.KeyPreview = true;
858 this.Name = "PDFViewForm";
859 this.Text = "PDFViewForm";
860 this.WindowState = System.Windows.Forms.FormWindowState.Maximized;
861 }
862 }
863}

Did you find this helpful?

Trial setup questions?

Ask experts on Discord

Need other help?

Contact Support

Pricing or product questions?

Contact Sales