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}
1Imports System
2Imports System.Drawing
3Imports System.Drawing.Drawing2D
4Imports System.Drawing.Printing
5Imports System.Collections
6Imports System.ComponentModel
7Imports System.Windows.Forms
8Imports pdftron
9Imports pdftron.PDF
10Imports pdftron.Common
11Imports System.Windows.Forms.VisualStyles.VisualStyleElement
12
13Public Class PDFViewForm
14
15 Inherits System.Windows.Forms.Form
16
17 ' <summary>
18 ' Required designer variable.
19 ' </summary>
20 Private components As System.ComponentModel.Container = Nothing
21
22#If CUSTOM_NAV Then
23
24 'The following variables are used for custom page navigation pane...
25 Private _pdfdoc_tab As System.Windows.Forms.TabControl
26 Private _bookmarks_tab As System.Windows.Forms.TabPage
27 Private _pages_tab As System.Windows.Forms.TabPage
28 Private _layers_tab As System.Windows.Forms.TabPage
29 Private bookmark_tree As System.Windows.Forms.TreeView
30 Private layer_tree As System.Windows.Forms.TreeView
31 Private splitter1 As System.Windows.Forms.Splitter
32 Private _thumbview As ThumbView = Nothing 'Custom thumbnail view.
33
34#End If
35
36 Private _pdfdoc As PDFDoc = Nothing ' Currently open PDF document.
37 Private _pdfview As MyPDFView = Nothing ' Main PDF view.
38
39 Public Sub New(ByVal main_form As MainForm)
40
41 Me.MdiParent = main_form
42
43 ' Create the main PDFViewCtrl control (we do it here manually for greater control)
44 _pdfview = New MyPDFView(Me)
45 _pdfview.Location = New System.Drawing.Point(0, 0) 'Added 'System.Drawing' to distinguish from PDF.Point to resolve compilaiton error
46 _pdfview.Dock = System.Windows.Forms.DockStyle.Fill
47
48 'Optional: Set the error and current page delegates...
49 _pdfview.SetErrorReportHandler(AddressOf ErrorMsg, Nothing)
50 _pdfview.SetCurrentPageHandler(AddressOf UpdateStatusBar, main_form)
51 Controls.Add(_pdfview)
52
53 ' Create other controls created using Windows Form Designer
54 InitializeComponent()
55
56 End Sub
57
58 Public Function OpenPDF(ByVal filename As String) As Boolean
59 Try
60 Try
61 ' Try to open as a PDF document
62 _pdfdoc = New PDFDoc(filename)
63 Catch ex As Exception
64 ' Try to open as a PNG, JPEG, TIF, BMP, GIF, etc.
65 _pdfdoc = OpenImage(filename)
66
67 If _pdfdoc Is Nothing Then
68
69 ' rethrow the original exception
70 Throw ex
71 End If
72 End Try
73
74 If Not _pdfdoc.InitSecurityHandler Then ' In case _pdfdoc is encrypted
75 MessageBox.Show("Document authentication error", "PDFViewCtrl Error")
76 Return False
77 End If
78
79#If CUSTOM_NAV Then
80
81 ' Populates a custom bookmark tree control with bookmark nodes (if any).
82 Dim root As Bookmark = _pdfdoc.GetFirstBookmark()
83 If root.IsValid Then
84 bookmark_tree.BeginUpdate()
85 FillBookmarkTree(root, bookmark_tree.Nodes)
86 bookmark_tree.EndUpdate()
87 Else
88 ' Optional: Uncomment the following line to hide the bookmark
89 ' tab if the document does not contain bookmarks?:
90 ' _pdfdoc_tab.Hide()
91 End If
92
93#End If
94
95 ' Optional: Set page view and page presentation mode.
96 ' _pdfview.SetPagePresentationMode(PDFViewCtrl.PagePresentationMode.e_single_page)
97 ' _pdfview.SetPageViewMode(PDFViewCtrl.PageViewMode.e_fit_page)
98
99 If _pdfdoc.GetPageCount() > 2000 Then
100
101 ' If the document has many pages use single page mode to seed up initial rendering.
102 _pdfview.SetPagePresentationMode(PDFViewCtrl.PagePresentationMode.e_single_page)
103
104 End If
105
106 _pdfview.SetDoc(_pdfdoc)
107
108#If CUSTOM_NAV Then
109
110 _thumbview.SetDoc(_pdfdoc, _pdfview)
111
112#End If
113
114 SetToolMode(MyPDFView._base_tool_mode, MyPDFView._tool_mode)
115 Catch ex As PDFNetException
116
117 MessageBox.Show(ex.Message)
118 Return False
119
120 Catch ex As Exception
121
122 MessageBox.Show(ex.ToString)
123 Return False
124
125 End Try
126
127 Me.Text = filename ' Set the title
128
129 Return True
130
131 End Function
132
133 ' A utility function used to display other images types besides PDF
134 ' inside MyPDFView. This functionality can be used to display TIF, JPEG,
135 ' BMP, PNG, etc.
136 Public Function OpenImage(ByVal filename As String) As PDFDoc
137
138 Try
139 Dim pdfDoc As PDFDoc = New PDFDoc ' create new document
140 Dim f As ElementBuilder = New ElementBuilder
141 Dim writer As ElementWriter = New ElementWriter
142 Dim page As Page = pdfDoc.PageCreate ' Add a blank page
143 writer.Begin(page)
144
145 ' Add image to the document.
146 Dim img As pdftron.PDF.Image = pdftron.PDF.Image.Create(pdfDoc.GetSDFDoc(), filename)
147
148 ' get image rectangle
149 Dim imgBox As Rect = New Rect(0, 0, img.GetImageWidth, img.GetImageHeight)
150 Dim scaledBox As Rect = New Rect
151 Dim scaleFactor As Double
152 If imgBox.Height / imgBox.Width > 792 / 612 Then
153 scaleFactor = imgBox.Height / 792
154 Else
155 scaleFactor = imgBox.Width / 612
156 End If
157
158 scaledBox.x2 = imgBox.x2 / scaleFactor
159 scaledBox.y2 = imgBox.y2 / scaleFactor
160
161 ' set crop and media box of this page to fit with the scaled image
162 page.SetCropBox(scaledBox)
163 page.SetMediaBox(scaledBox)
164
165 ' create the image element and add it to the page
166 Dim width As Integer = CType(scaledBox.Width, Integer)
167 Dim height As Integer = CType(scaledBox.Height, Integer)
168 Dim offsetX As Integer = 0
169 Dim offsetY As Integer = 0
170 Dim element As Element = f.CreateImage(img, New Matrix2D(width, 0, 0, height, offsetX, offsetY))
171 writer.WritePlacedElement(element)
172 writer.End() ' Finish writing to the page
173 pdfDoc.PagePushBack(page)
174
175 Return pdfDoc
176
177 Catch ex As Exception
178
179 ' MessageBox.Show(ex.ToString)
180 Return Nothing
181 End Try
182
183 End Function
184
185 Public Function GetPDFDoc() As PDFDoc
186 If _pdfview Is Nothing Then
187 Return Nothing
188 Else
189 Return _pdfview.GetDoc
190 End If
191 End Function
192 Public Sub FitPage()
193 _pdfview.SetPageViewMode(PDFViewCtrl.PageViewMode.e_fit_page)
194 End Sub
195
196 Public Sub FitWidth()
197 _pdfview.SetPageViewMode(PDFViewCtrl.PageViewMode.e_fit_width)
198 End Sub
199
200 Public Sub ZoomIn()
201 _pdfview.SetZoom(_pdfview.GetZoom * 2)
202 End Sub
203
204 Public Sub ZoomOut()
205 _pdfview.SetZoom(_pdfview.GetZoom / 2)
206 End Sub
207
208 Public Sub FirstPage()
209 _pdfview.GotoFirstPage()
210 End Sub
211
212 Public Sub PrevPage()
213 _pdfview.GotoPreviousPage()
214 End Sub
215
216 Public Sub NextPage()
217 _pdfview.GotoNextPage()
218 End Sub
219
220 Public Sub LastPage()
221 _pdfview.GotoLastPage()
222 End Sub
223
224 Public Sub PageSingle()
225 _pdfview.SetPagePresentationMode(PDFViewCtrl.PagePresentationMode.e_single_page)
226 End Sub
227 Public Sub PageSingleContinuous()
228 _pdfview.SetPagePresentationMode(PDFViewCtrl.PagePresentationMode.e_single_continuous)
229 End Sub
230
231 Public Sub PageFacingContinuous()
232 _pdfview.SetPagePresentationMode(PDFViewCtrl.PagePresentationMode.e_facing_continuous)
233 End Sub
234
235 Public Sub PageFacing()
236 _pdfview.SetPagePresentationMode(PDFViewCtrl.PagePresentationMode.e_facing)
237 End Sub
238
239 Public Sub RotateClockwise()
240 _pdfview.RotateClockwise()
241 End Sub
242
243 Public Sub RotateCounterClockwise()
244 _pdfview.RotateCounterClockwise()
245 End Sub
246 Public Sub SetAntiAliasing(ByVal anti_alias As Boolean)
247 _pdfview.SetAntiAliasing(anti_alias)
248 _pdfview.Update()
249 End Sub
250
251 Public Sub SetRasterizer(ByVal built_in As Boolean)
252 If built_in Then
253 _pdfview.SetRasterizerType(PDFRasterizer.Type.e_BuiltIn)
254 Else
255 _pdfview.SetRasterizerType(PDFRasterizer.Type.e_GDIPlus)
256 End If
257
258 _pdfview.Update()
259 End Sub
260
261 Public Sub SetSmoothImages(ByVal smooth_images As Boolean)
262 _pdfview.SetImageSmoothing(smooth_images)
263 _pdfview.Update()
264 End Sub
265
266 Public Sub Save(ByVal filename As String)
267 If _pdfdoc Is Nothing Then
268 Return
269 End If
270
271 _pdfdoc.Lock()
272
273 Try
274 If Not (_pdfview Is Nothing) Then
275 ' Check if there are any annotations that need to
276 ' be merged with the document.
277 If Not (_pdfview._freehand_markup Is Nothing) Then
278 For Each itr As DictionaryEntry In _pdfview._freehand_markup
279 Dim annot_page_num As Integer = CType(itr.Key, Integer)
280 Dim pg As Page = _pdfdoc.GetPage(annot_page_num)
281 If Not pg Is Nothing Then
282 Dim annot As FreeHandAnnot = CType(itr.Value, FreeHandAnnot)
283 annot.DrawAnnots(pg, Pens.Red)
284 End If
285 Next
286
287 _pdfview._freehand_markup = Nothing
288 _pdfview.Invalidate()
289 _pdfview.Update()
290 End If
291 End If
292
293 _pdfdoc.Save(filename, pdftron.SDF.SDFDoc.SaveOptions.e_remove_unused)
294
295 Catch ex As Exception
296 MessageBox.Show(ex.ToString(), "Error during the Save")
297 End Try
298
299 _pdfdoc.Unlock()
300
301 End Sub
302
303 Public Sub SaveAs()
304 If Not (_pdfdoc Is Nothing) AndAlso Not (_pdfview Is Nothing) Then
305
306 'opens a save dialog
307 Dim dlg As SaveFileDialog = New SaveFileDialog
308 dlg.Filter = "PDF Files (*.pdf)|*.pdf|All Files (*.*)|*.*"
309 dlg.DefaultExt = ".pdf"
310 dlg.FileName = Text
311 Dim res As DialogResult = dlg.ShowDialog
312 If res = DialogResult.OK Then
313 'saves the file
314 Me.Save(dlg.FileName)
315 End If
316 End If
317 End Sub
318
319 Protected Overloads Overrides Sub OnClosing(ByVal e As CancelEventArgs)
320
321 'called when user closes a document
322 If Not (_pdfdoc Is Nothing) AndAlso Not (_pdfview Is Nothing) AndAlso (_pdfdoc.IsModified OrElse Not (_pdfview._freehand_markup Is Nothing)) Then
323
324 'if the document exists and is modified then ask the user
325 'whether or not to save it
326 Dim save As DialogResult = MessageBox.Show("Would you like to save the changes to the document?", "PDFViewCtrl", MessageBoxButtons.YesNoCancel)
327
328 If save = DialogResult.Yes Then
329 'opens a save dialog
330 Dim dlg As SaveFileDialog = New SaveFileDialog
331 dlg.Filter = "PDF Files (*.pdf)|*.pdf|All Files (*.*)|*.*"
332 dlg.DefaultExt = ".pdf"
333 dlg.FileName = Text
334 Dim res As DialogResult = dlg.ShowDialog
335 If res = DialogResult.OK Then
336 'saves the file
337 Me.Save(dlg.FileName)
338 Else
339 If res = DialogResult.Cancel Then
340 e.Cancel = True
341 End If
342 End If
343 Else
344 If save = DialogResult.Cancel Then
345 e.Cancel = True
346 End If
347 End If
348
349 MyBase.OnClosing(e)
350 End If
351 End Sub
352
353 ' <summary>
354 ' Clean up any resources being used.
355 ' </summary>
356 Protected Overloads Overrides Sub Dispose(ByVal disposing As Boolean)
357 If disposing Then
358
359#If CUSTOM_NAV Then
360
361 _thumbview.Dispose() ' Close the thumbnail view.
362
363#End If
364
365 _pdfview.Dispose() ' Close the open PDF document in the view.
366 _pdfdoc.Dispose() ' Close the PDF document.
367 If Not (components Is Nothing) Then
368 components.Dispose()
369 End If
370 End If
371
372 MyBase.Dispose(disposing)
373 End Sub
374
375 ' <summary>
376 ' This callback method (delegate) was registered using _pdfview.SetErrorReportProc
377 ' in PDFViewCS constructor. The callback can be used to report any errors that may
378 ' occur during page rendering.
379 ' </summary>
380
381 Public Shared Sub ErrorMsg(ByVal message As String, ByVal obj As Object)
382 MessageBox.Show(message, "PDFViewCtrl Error")
383 End Sub
384
385#If CUSTOM_NAV Then 'Custom bookmark and PDF layer navigation sample
386
387 ' Handle the the bookmark select event (i.e. when the user selects a node in the bookmark tree).
388 Private Sub BookmarkTreeAfterSelect(ByVal sender As System.Object, ByVal e As System.Windows.Forms.TreeViewEventArgs) Handles bookmark_tree.AfterSelect
389 _pdfdoc.Lock()
390 Dim item As Bookmark = CType(e.Node.Tag, Bookmark)
391 Dim action As Action = item.GetAction
392 If action.IsValid Then ' Handle goto actions.
393 ' Other types of actions can be handled in similar way.
394 If action.GetType = action.Type.e_GoTo Then
395 Dim dest As Destination = action.GetDest
396 If dest.IsValid() Then
397 Dim page As Page = dest.GetPage
398 If Not page Is Nothing Then
399 _pdfview.SetCurrentPage(page.GetIndex)
400 End If
401 End If
402 End If
403 End If
404
405 _pdfdoc.Unlock()
406 End Sub
407
408 ' Populate the tree control with bookmark items.
409 Shared Sub FillBookmarkTree(ByVal item As Bookmark, ByVal nodes As TreeNodeCollection)
410 Dim i As Integer = 0
411 While item.IsValid
412 Dim new_node As TreeNode = New TreeNode(item.GetTitle)
413 nodes.Add(new_node)
414 new_node.Tag = item
415 If item.IsOpen Then
416 new_node.Expand()
417 End If
418 If item.HasChildren Then ' Recursively add children sub-trees
419 FillBookmarkTree(item.GetFirstChild, new_node.Nodes)
420 End If
421 item = item.GetNext
422 i = i + 1
423 End While
424 End Sub
425
426#End If
427
428 ' <summary>
429 ' This callback method (delegate) was registered using _pdfview.SetCurrentPageProc
430 ' in PDFViewCS constructor. The callback can be used to update the current page number
431 ' within GUI applications etc. In this case we update the status bar in the main form.
432 ' </summary>
433 Public Shared Sub UpdateStatusBar(ByVal current_page As Integer, ByVal num_pages As Integer, ByVal data As Object)
434 If Not (data Is Nothing) Then
435 Dim main_form As MainForm = CType(data, MainForm)
436 main_form._current_page = current_page
437 main_form._num_pages = num_pages
438 main_form.UpdateStatusBar(current_page, num_pages)
439 End If
440 End Sub
441
442 Public Sub SetToolMode(ByVal tool_mode As MyPDFView.CustomToolMode, ByVal custom_tool_mode As MyPDFView.CustomToolMode)
443 ' Set the custom tool mode.
444 MyPDFView._base_tool_mode = tool_mode
445 MyPDFView._tool_mode = custom_tool_mode
446 'Chaged by Kay April1------------------------
447 'Set built-in tool mode (pan, text select, or custom)
448 'Dim tm As PDFViewCtrl.ToolMode
449 'If (tool_mode = MyPDFView.CustomToolMode.e_pan) Then
450 ' tm = PDFViewCtrl.ToolMode.e_pan
451 'ElseIf (tool_mode = MyPDFView.CustomToolMode.e_text_struct_select) Then
452 ' tm = PDFViewCtrl.ToolMode.e_text_struct_select
453 'ElseIf (tool_mode = MyPDFView.CustomToolMode.e_text_rect_select) Then
454 ' tm = PDFViewCtrl.ToolMode.e_text_rect_select
455 'Else
456 ' tm = PDFViewCtrl.ToolMode.e_custom
457 'End If
458 'Chaged by Kay April1------------------------
459 _pdfview.SetToolMode(tool_mode)
460 End Sub
461
462 Protected Overloads Overrides Sub OnActivated(ByVal e As EventArgs)
463 If Not (_pdfview Is Nothing) Then
464 Dim main_form As MainForm = CType(Me.MdiParent, MainForm)
465 main_form._current_page = _pdfview.GetCurrentPage
466 main_form._num_pages = _pdfview.GetDoc.GetPageCount
467 main_form.UpdateStatusBar(_pdfview.GetCurrentPage(), _pdfview.GetDoc().GetPageCount())
468 End If
469 End Sub
470
471 Private Sub InitializeComponent()
472 Dim resources As System.Resources.ResourceManager = New System.Resources.ResourceManager(GetType(PDFViewForm))
473 'PDFViewForm
474 '
475 Me.BackColor = System.Drawing.SystemColors.Control
476 Me.Cursor = System.Windows.Forms.Cursors.Hand
477 Me.Icon = CType(resources.GetObject("$this.Icon"), System.Drawing.Icon)
478 Me.KeyPreview = True
479 Me.Name = "PDFViewForm"
480 Me.Text = "PDFViewForm"
481 Me.WindowState = System.Windows.Forms.FormWindowState.Maximized
482 End Sub
483
484 Public Sub Export()
485 Dim temp As ExportDialog = New ExportDialog(Me._pdfdoc)
486 End Sub
487
488 Public Sub CopySelectedText()
489 _pdfview.OnTextCopy(Nothing, Nothing)
490 End Sub
491
492 Public Sub SelectAll()
493 _pdfview.SelectAll()
494 End Sub
495
496 Public Sub DeselectAll()
497 _pdfview.ClearSelection()
498 End Sub
499
500 Public Sub FindText()
501 _pdfview.Find() 'Use the build in Find text dialog.
502 End Sub
503
504 ' Private members used for print support -------------------------
505 ' In this sample, PDFDraw object is used to implement print support.
506 Private pdfdraw As PDFDraw = Nothing
507 Private print_page_itr As PageIterator
508
509 Public Sub Print()
510 Try
511
512#If CUSTOM_PRINT Then
513
514 Dim print_dlg As PrintDialog = New PrintDialog
515 print_dlg.AllowSomePages = True
516 print_dlg.Document = print_doc
517 If (print_dlg.ShowDialog() = DialogResult.OK) Then
518 pdfdraw = new PDFDraw
519 pdfdraw.SetPrintMode(True)
520 _print_doc.Print()
521 pdfdraw.Dispose()
522 pdfdraw = Nothing
523 End If
524
525#Else
526
527 _pdfview.Print()
528
529#End If
530
531 Catch ex As Exception
532 MessageBox.Show(ex.ToString())
533 End Try
534 End Sub
535
536 ' Me.print_doc.BeginPrint += New System.Drawing.Printing.PrintEventHandler(this.OnBeginPDFPrint)
537 ' Me.print_doc.PrintPage += New System.Drawing.Printing.PrintPageEventHandler(this.OnPrintPDFPage)
538
539#If CUSTOM_PRINT Then
540
541 Private Sub OnBeginPDFPrint(ByVal sender As System.Object, ByVal ev As System.Drawing.Printing.PrintEventArgs) Handles print_doc.BeginPrint
542 Dim doc As PDFDoc = GetPDFDoc()
543 If doc Is Nothing Then
544 MessageBox.Show("Error: Print document is not selected.")
545 Return
546 End If
547 print_page_itr = doc.GetPageIterator()
548
549 ' PDFNet includes two different rasterizer implementations.
550 '
551 ' The two implementations offer a trade-off between print
552 ' speed and accuracy/quality, as well as a trade-off between
553 ' vector and raster output.
554 '
555 ' e_GDIPlus rasterizer can be used to render the page
556 ' using Windows GDI+, whereas e_BuiltIn rasterizer can
557 ' be used to render bitmaps using platform-independent
558 ' graphics engine (in this case images are always converted
559 ' to bitmap prior to printing).
560 pdfdraw.SetRasterizerType(PDFRasterizer.Type.e_GDIPlus)
561
562 ' You can uncomment the following lines in order to use
563 ' built-in, platform-independent rasterizer instead of GDI+.
564 ' pdfdraw.SetRasterizerType(PDFRasterizer.Type.e_BuiltIn)
565 ' pdfdraw.SetDPI(200)
566 End Sub
567
568#if NET_1_1
569
570 <System.Runtime.InteropServices.DllImport("gdi32.dll")> Private Shared Function GetDeviceCaps(ByVal hdc As IntPtr, ByVal nIndex As Integer) As Integer
571 End Function
572
573 Private Const PHYSICALOFFSETX As Integer = 112
574 Private Const PHYSICALOFFSETY As Integer = 113
575
576 #endif
577
578 Private Sub OnPrintPDFPage(ByVal sender As Object, ByVal ev As PrintPageEventArgs)'Handles print_doc.PrintPage
579 Dim gr As Graphics = ev.Graphics
580 gr.PageUnit = GraphicsUnit.Inch
581 Dim use_hard_margins As Boolean =False
582 Dim rectPage As Rectangle=ev.PageBounds 'print without margins
583 Dim left As Double
584 Dim right As Double
585 Dim top As Double
586 Dim bottom As Double
587 If use_hard_margins Is True Then
588
589#if NET_1_1
590
591 ' This code is used to obtain printer hard margins when running on .NET 1.1x or below.
592 Dim hdc As IntPtr = new IntPtr
593 hdc = ev.Graphics.GetHdc(); 'Get handle to device context.
594 Dim hardMarginX As Double = GetDeviceCaps(hdc, PHYSICALOFFSETX)
595 Dim hardMarginY As Double = GetDeviceCaps(hdc, PHYSICALOFFSETY)
596 ev.Graphics.ReleaseHdc(hdc) 'Release handle to device context.
597
598#else
599
600 ' If you are running on .NET Framework 2.x or above, you can directly access 'hard margin' property.
601 Dim hardMarginX As Double = ev.PageSettings.HardMarginX
602 Dim hardMarginY As Double = ev.PageSettings.HardMarginY
603
604#endif
605
606 left = (rectPage.Left - hardMarginX) / 100.0
607 right = (rectPage.Right - hardMarginX) / 100.0
608 top = (rectPage.Top - hardMarginY) / 100.0
609 bottom = (rectPage.Bottom - hardMarginY) / 100.0
610 Else
611 left= rectPage.Left / 100.0;
612 right = rectPage.Right / 100.0;
613 top = rectPage.Top / 100.0;
614 bottom= rectPage.Bottom / 100.0;
615 End If
616
617 'The above page dimensions are in inches. We need to convert
618 'the page dimensions to PDF units (or points). One point is
619 '1/72 of an inch.
620 Dim rect As pdftron.PDF.Rect = new Rect(left*72, bottom*72, right*72, top*72)
621 Dime pdfdoc As PDFDoc = GetPDFDoc()
622 pdfdoc.Lock()
623
624 Try
625 If print_page_itr.HasNext() Then
626 _pdfdraw.DrawInRect(print_page_itr.Current(), gr, rect)
627
628 'Move to the next page, or finish printing
629 print_page_itr.Next()
630 ev.HasMorePages = print_page_itr.HasNext()
631 else ev.HasMorePages = False
632 Catch ex As Exception
633 MessageBox.Show("Printing Error: " + ex.ToString)
634 End Try
635 pdfdoc.Unlock()
636 End Sub
637
638#End If
639
640End Class
Did you find this helpful?
Trial setup questions?
Ask experts on DiscordNeed other help?
Contact SupportPricing or product questions?
Contact Sales