Imports System Imports System.Drawing Imports System.Drawing.Drawing2D Imports System.Drawing.Printing Imports System.Collections Imports System.ComponentModel Imports System.Windows.Forms Imports PDFTRON Imports PDFTRON.PDF Imports PDFTRON.Common Public Class PDFViewForm Inherits System.Windows.Forms.Form ' ' Required designer variable. ' Private components As System.ComponentModel.Container = Nothing Private _pdfdoc_tab As System.Windows.Forms.TabControl Private _bookmarks_tab As System.Windows.Forms.TabPage Private _pages_tab As System.Windows.Forms.TabPage Private WithEvents bookmark_tree As System.Windows.Forms.TreeView Private splitter1 As System.Windows.Forms.Splitter Private _pdfdoc As PDFDoc = Nothing ' Currently open PDF document. Private _thumbview As ThumbView = Nothing ' Thumbnail view. Private _pdfview As MyPDFView = Nothing ' Main PDF view. Private WithEvents print_doc As System.Drawing.Printing.PrintDocument Public Sub New(ByVal main_form As MainForm) Me.MdiParent = main_form ' Create the main PDFView control (we do it here manually for greater control) _pdfview = New MyPDFView(Me) _pdfview.Location = New Point(0, 0) _pdfview.Dock = System.Windows.Forms.DockStyle.Fill _pdfview.SetErrorReportProc(AddressOf ErrorMsg, Nothing) _pdfview.SetCurrentPageProc(AddressOf UpdateStatusBar, main_form) Controls.Add(_pdfview) ' Create other controls created using Windows Form Designer InitializeComponent() End Sub Public Function OpenPDF(ByVal filename As String) As Boolean Try Try ' Try to open as a PDF document _pdfdoc = New PDFDoc(filename) Catch ex As Exception ' Try to open as a PNG, JPEG, TIF, BMP, GIF, etc. _pdfdoc = OpenImage(filename) If _pdfdoc Is Nothing Then ' rethrow the original exception Throw ex End If End Try If Not _pdfdoc.InitSecurityHandler Then ' In case _pdfdoc is encrypted MessageBox.Show("Document authentication error", "PDFView Error") Return False End If ' Populates a bookmark tree control with bookmark nodes (if any). Dim root As Bookmark = _pdfdoc.GetFirstBookmark() If root.IsValid Then bookmark_tree.BeginUpdate() FillBookmarkTree(root, bookmark_tree.Nodes) bookmark_tree.EndUpdate() Else ' Optional: Uncomment the following line to hide the bookmark ' tab if the document does not contain bookmarks?: ' _pdfdoc_tab.Hide() End If ' Optional: Set page view and page presentation mode. ' _pdfview.SetPagePresentationMode(PDFView.PagePresentationMode.e_single_page) ' _pdfview.SetPageViewMode(PDFView.PageViewMode.e_fit_page) If _pdfdoc.GetPageCount() > 2000 Then ' If the document has many pages use single page mode to seed up initial rendering. _pdfview.SetPagePresentationMode(PDFView.PagePresentationMode.e_single_page) End If _pdfview.SetDoc(_pdfdoc) _thumbview.SetDoc(_pdfdoc, _pdfview) SetToolMode(MyPDFView._tool_mode) Catch ex As PDFNetException MessageBox.Show(ex.Message) Return False Catch ex As Exception MessageBox.Show(ex.ToString) Return False End Try Me.Text = filename ' Set the title Return True End Function ' A utility function used to display other images types besides PDF ' inside MyPDFView. This functionality can be used to display TIF, JPEG, ' BMP, PNG, etc. Public Function OpenImage(ByVal filename As String) As PDFDoc Try Dim pdfDoc As PDFDoc = New PDFDoc ' create new document Dim f As ElementBuilder = New ElementBuilder Dim writer As ElementWriter = New ElementWriter Dim page As Page = pdfDoc.PageCreate ' Add a blank page writer.Begin(page) ' Add image to the document. Dim img As PDFTRON.PDF.Image = PDFTRON.PDF.Image.Create(pdfDoc.GetSDFDoc(), filename) ' get image rectangle Dim imgBox As Rect = New Rect(0, 0, img.GetImageWidth, img.GetImageHeight) Dim scaledBox As Rect = New Rect Dim scaleFactor As Double If imgBox.Height / imgBox.Width > 792 / 612 Then scaleFactor = imgBox.Height / 792 Else scaleFactor = imgBox.Width / 612 End If scaledBox.x2 = imgBox.x2 / scaleFactor scaledBox.y2 = imgBox.y2 / scaleFactor ' set crop and media box of this page to fit with the scaled image page.SetCropBox(scaledBox) page.SetMediaBox(scaledBox) ' create the image element and add it to the page Dim width As Integer = CType(scaledBox.Width, Integer) Dim height As Integer = CType(scaledBox.Height, Integer) Dim offsetX As Integer = 0 Dim offsetY As Integer = 0 Dim element As Element = f.CreateImage(img, New Matrix2D(width, 0, 0, height, offsetX, offsetY)) writer.WritePlacedElement(element) writer.End() ' Finish writing to the page pdfDoc.PagePushBack(page) Return pdfDoc Catch ex As Exception ' MessageBox.Show(ex.ToString) Return Nothing End Try End Function Public Function GetPDFDoc() As PDFDoc If _pdfview Is Nothing Then Return Nothing Else Return _pdfview.GetDoc End If End Function Public Sub FitPage() _pdfview.SetPageViewMode(PDFView.PageViewMode.e_fit_page) End Sub Public Sub FitWidth() _pdfview.SetPageViewMode(PDFView.PageViewMode.e_fit_width) End Sub Public Sub ZoomIn() _pdfview.SetZoom(_pdfview.GetZoom * 2) End Sub Public Sub ZoomOut() _pdfview.SetZoom(_pdfview.GetZoom / 2) End Sub Public Sub FirstPage() _pdfview.GotoFirstPage() End Sub Public Sub PrevPage() _pdfview.GotoPreviousPage() End Sub Public Sub NextPage() _pdfview.GotoNextPage() End Sub Public Sub LastPage() _pdfview.GotoLastPage() End Sub Public Sub PageSingle() _pdfview.SetPagePresentationMode(PDFView.PagePresentationMode.e_single_page) End Sub Public Sub PageSingleContinuous() _pdfview.SetPagePresentationMode(PDFView.PagePresentationMode.e_single_continuous) End Sub Public Sub PageFacingContinuous() _pdfview.SetPagePresentationMode(PDFView.PagePresentationMode.e_facing_continuous) End Sub Public Sub PageFacing() _pdfview.SetPagePresentationMode(PDFView.PagePresentationMode.e_facing) End Sub Public Sub RotateClockwise() _pdfview.RotateClockwise() End Sub Public Sub RotateCounterClockwise() _pdfview.RotateCounterClockwise() End Sub Public Sub SetAntiAliasing(ByVal anti_alias As Boolean) _pdfview.SetAntiAliasing(anti_alias) _pdfview.Update() End Sub Public Sub SetRasterizer(ByVal built_in As Boolean) If built_in Then _pdfview.SetRasterizerType(PDFRasterizer.Type.e_BuiltIn) Else _pdfview.SetRasterizerType(PDFRasterizer.Type.e_GDIPlus) End If _pdfview.Update() End Sub Public Sub SetSmoothImages(ByVal smooth_images As Boolean) _pdfview.SetImageSmoothing(smooth_images) _pdfview.Update() End Sub Public Sub Save(ByVal filename As String) If _pdfdoc Is Nothing Then Return End If _pdfdoc.Lock() Try If Not (_pdfview Is Nothing) Then ' Check if there are any annotations that need to ' be merged with the document. If Not (_pdfview._freehand_markup Is Nothing) Then For Each itr As DictionaryEntry In _pdfview._freehand_markup Dim annot_page_num As Integer = CType(itr.Key, Integer) Dim pg As Page = _pdfdoc.GetPage(annot_page_num) If Not pg Is Nothing Then Dim annot As FreeHandAnnot = CType(itr.Value, FreeHandAnnot) annot.DrawAnnots(pg, Pens.Red) End If Next _pdfview._freehand_markup = Nothing _pdfview.Invalidate() _pdfview.Update() End If End If _pdfdoc.Save(filename, PDFTRON.SDF.SDFDoc.SaveOptions.e_remove_unused) Catch ex As Exception MessageBox.Show(ex.ToString(), "Error during the Save") End Try _pdfdoc.Unlock() End Sub Public Sub SaveAs() If Not (_pdfdoc Is Nothing) AndAlso Not (_pdfview Is Nothing) Then 'opens a save dialog Dim dlg As SaveFileDialog = New SaveFileDialog dlg.Filter = "PDF Files (*.pdf)|*.pdf|All Files (*.*)|*.*" dlg.DefaultExt = ".pdf" dlg.FileName = Text Dim res As DialogResult = dlg.ShowDialog If res = DialogResult.OK Then 'saves the file Me.Save(dlg.FileName) End If End If End Sub Protected Overloads Overrides Sub OnClosing(ByVal e As CancelEventArgs) 'called when user closes a document If Not (_pdfdoc Is Nothing) AndAlso Not (_pdfview Is Nothing) AndAlso (_pdfdoc.IsModified OrElse Not (_pdfview._freehand_markup Is Nothing)) Then 'if the document exists and is modified then ask the user 'whether or not to save it Dim save As DialogResult = MessageBox.Show("Would you like to save the changes to the document?", "PDFView", MessageBoxButtons.YesNoCancel) If save = DialogResult.Yes Then 'opens a save dialog Dim dlg As SaveFileDialog = New SaveFileDialog dlg.Filter = "PDF Files (*.pdf)|*.pdf|All Files (*.*)|*.*" dlg.DefaultExt = ".pdf" dlg.FileName = Text Dim res As DialogResult = dlg.ShowDialog If res = DialogResult.OK Then 'saves the file Me.Save(dlg.FileName) Else If res = DialogResult.Cancel Then e.Cancel = True End If End If Else If save = DialogResult.Cancel Then e.Cancel = True End If End If MyBase.OnClosing(e) End If End Sub ' ' Clean up any resources being used. ' Protected Overloads Overrides Sub Dispose(ByVal disposing As Boolean) If disposing Then _thumbview.Close() ' Close the thumbnail view. _pdfview.Close() ' Close the open PDF document in the view. _pdfdoc.Close() ' Close the PDF document. If Not (components Is Nothing) Then components.Dispose() End If End If MyBase.Dispose(disposing) End Sub ' ' This callback method (delegate) was registered using _pdfview.SetErrorReportProc ' in PDFViewCS constructor. The callback can be used to report any errors that may ' occur during page rendering. ' Public Shared Sub ErrorMsg(ByVal message As String, ByVal obj As Object) MessageBox.Show(message, "PDFView Error") End Sub ' Handle the the bookmark select event (i.e. when the user selects a node in the bookmark tree). Private Sub BookmarkTreeAfterSelect(ByVal sender As System.Object, ByVal e As System.Windows.Forms.TreeViewEventArgs) Handles bookmark_tree.AfterSelect _pdfdoc.Lock() Dim item As Bookmark = CType(e.Node.Tag, Bookmark) Dim action As Action = item.GetAction If action.IsValid Then ' Handle goto actions. ' Other types of actions can be handled in similar way. If action.GetType = action.Type.e_GoTo Then Dim dest As Destination = action.GetDest If dest.IsValid() Then Dim page As Page = dest.GetPage _pdfview.SetCurrentPage(page.GetIndex) End If End If End If _pdfdoc.Unlock() End Sub ' Populate the tree control with bookmark items. Shared Sub FillBookmarkTree(ByVal item As Bookmark, ByVal nodes As TreeNodeCollection) Dim i As Integer = 0 While item.IsValid Dim new_node As TreeNode = New TreeNode(item.GetTitle) nodes.Add(new_node) new_node.Tag = item If item.IsOpen Then new_node.Expand() End If If item.HasChildren Then ' Recursively add children sub-trees FillBookmarkTree(item.GetFirstChild, new_node.Nodes) End If item = item.GetNext i = i + 1 End While End Sub ' ' This callback method (delegate) was registered using _pdfview.SetCurrentPageProc ' in PDFViewCS constructor. The callback can be used to update the current page number ' within GUI applications etc. In this case we update the status bar in the main form. ' Public Shared Sub UpdateStatusBar(ByVal current_page As Integer, ByVal num_pages As Integer, ByVal data As Object) If Not (data Is Nothing) Then Dim main_form As MainForm = CType(data, MainForm) main_form._current_page = current_page main_form._num_pages = num_pages main_form.UpdateStatusBar() End If End Sub Public Sub SetToolMode(ByVal tool_mode As MyPDFView.CustomToolMode) ' Set the custom tool mode. MyPDFView._tool_mode = tool_mode ' Set built-in tool mode (pan, text select, or custom) Dim tm As PDFView.ToolMode If (tool_mode = MyPDFView.CustomToolMode.e_pan) Then tm = PDFView.ToolMode.e_pan ElseIf (tool_mode = MyPDFView.CustomToolMode.e_text_struct_select) Then tm = PDFView.ToolMode.e_text_struct_select ElseIf (tool_mode = MyPDFView.CustomToolMode.e_text_rect_select) Then tm = PDFView.ToolMode.e_text_rect_select Else tm = PDFView.ToolMode.e_custom End If _pdfview.SetToolMode(tm) End Sub Protected Overloads Overrides Sub OnActivated(ByVal e As EventArgs) If Not (_pdfview Is Nothing) Then Dim main_form As MainForm = CType(Me.MdiParent, MainForm) main_form._current_page = _pdfview.GetCurrentPage main_form._num_pages = _pdfview.GetDoc.GetPageCount main_form.UpdateStatusBar() End If End Sub Private Sub InitializeComponent() Dim resources As System.Resources.ResourceManager = New System.Resources.ResourceManager(GetType(PDFViewForm)) Me._pdfdoc_tab = New System.Windows.Forms.TabControl Me._bookmarks_tab = New System.Windows.Forms.TabPage Me.bookmark_tree = New System.Windows.Forms.TreeView Me._pages_tab = New System.Windows.Forms.TabPage Me.splitter1 = New System.Windows.Forms.Splitter Me._thumbview = New ThumbView Me._pdfdoc_tab.SuspendLayout() Me._bookmarks_tab.SuspendLayout() Me.SuspendLayout() ' '_pdfdoc_tab ' Me._pdfdoc_tab.Controls.Add(Me._bookmarks_tab) Me._pdfdoc_tab.Controls.Add(Me._pages_tab) Me._pdfdoc_tab.Dock = System.Windows.Forms.DockStyle.Left Me._pdfdoc_tab.Location = New System.Drawing.Point(0, 0) Me._pdfdoc_tab.Name = "_pdfdoc_tab" Me._pdfdoc_tab.SelectedIndex = 0 Me._pdfdoc_tab.Size = New System.Drawing.Size(200, 320) Me._pdfdoc_tab.TabIndex = 0 ' '_bookmarks_tab ' Me._bookmarks_tab.Controls.Add(Me.bookmark_tree) Me._bookmarks_tab.Location = New System.Drawing.Point(4, 25) Me._bookmarks_tab.Name = "_bookmarks_tab" Me._bookmarks_tab.Size = New System.Drawing.Size(192, 291) Me._bookmarks_tab.TabIndex = 0 Me._bookmarks_tab.Text = "Bookmarks" ' 'bookmark_tree ' Me.bookmark_tree.Dock = System.Windows.Forms.DockStyle.Fill Me.bookmark_tree.ImageIndex = -1 Me.bookmark_tree.Location = New System.Drawing.Point(0, 0) Me.bookmark_tree.Name = "bookmark_tree" Me.bookmark_tree.SelectedImageIndex = -1 Me.bookmark_tree.Size = New System.Drawing.Size(192, 291) Me.bookmark_tree.TabIndex = 0 ' '_pages_tab ' Me._pages_tab.Controls.Add(Me._thumbview) Me._pages_tab.Location = New System.Drawing.Point(4, 25) Me._pages_tab.Name = "_pages_tab" Me._pages_tab.Size = New System.Drawing.Size(192, 291) Me._pages_tab.TabIndex = 1 Me._pages_tab.Text = "Pages" ' 'splitter1 ' Me.splitter1.Location = New System.Drawing.Point(200, 0) Me.splitter1.Name = "splitter1" Me.splitter1.Size = New System.Drawing.Size(3, 320) Me.splitter1.TabIndex = 1 Me.splitter1.TabStop = False ' '_thumbview ' Me._thumbview.Dock = System.Windows.Forms.DockStyle.Fill Me._thumbview.Location = New System.Drawing.Point(0, 0) Me._thumbview.Name = "_thumbview" Me._thumbview.TabIndex = 0 ' 'PDFViewForm ' Me.AutoScaleBaseSize = New System.Drawing.Size(6, 15) Me.BackColor = System.Drawing.SystemColors.Control Me.ClientSize = New System.Drawing.Size(448, 320) Me.Controls.Add(Me.splitter1) Me.Controls.Add(Me._pdfdoc_tab) Me.Cursor = System.Windows.Forms.Cursors.Hand Me.Icon = CType(resources.GetObject("$this.Icon"), System.Drawing.Icon) Me.Name = "PDFViewForm" Me.Text = "PDFViewForm" Me.WindowState = System.Windows.Forms.FormWindowState.Maximized Me._pdfdoc_tab.ResumeLayout(False) Me._bookmarks_tab.ResumeLayout(False) Me.ResumeLayout(False) ' ' print_doc ' Me.print_doc = New System.Drawing.Printing.PrintDocument End Sub Public Sub Export() Dim temp As ExportDialog = New ExportDialog(Me._pdfdoc) End Sub Public Sub CopySelectedText() _pdfview.OnTextCopy(Nothing, Nothing) End Sub Public Sub SelectAll() _pdfview.SelectAll() End Sub Public Sub DeselectAll() _pdfview.ClearSelection() End Sub Private _find_text_dlg As FindTextDlg = Nothing Public Sub FindText() If _find_text_dlg Is Nothing Then _find_text_dlg = New FindTextDlg _find_text_dlg._pdfview = _pdfview End If If _find_text_dlg.Visible Then _find_text_dlg.Focus() Else _find_text_dlg.Show() End If End Sub ' Private members used for print support ------------------------- ' In this sample, PDFDraw object is used to implement print support. Private pdfdraw As pdfdraw = Nothing Private print_page_itr As PageIterator Public Sub Print() Try Dim print_dlg As PrintDialog = New PrintDialog print_dlg.AllowSomePages = True print_dlg.Document = print_doc If (print_dlg.ShowDialog() = DialogResult.OK) Then pdfdraw = New PDFDraw print_doc.Print() pdfdraw.Dispose() pdfdraw = Nothing End If Catch ex As Exception MessageBox.Show(ex.ToString()) End Try End Sub '' Me.print_doc.BeginPrint += New System.Drawing.Printing.PrintEventHandler(this.OnBeginPDFPrint) ' Me.print_doc.PrintPage += New System.Drawing.Printing.PrintPageEventHandler(this.OnPrintPDFPage) Private Sub OnBeginPDFPrint(ByVal sender As System.Object, ByVal ev As System.Drawing.Printing.PrintEventArgs) Handles print_doc.BeginPrint Dim doc As PDFDoc = GetPDFDoc() If doc Is Nothing Then MessageBox.Show("Error: Print document is not selected.") Return End If print_page_itr = doc.GetPageIterator() ' PDFNet includes two different rasterizer implementations. ' ' The two implementations offer a trade-off between print ' speed and accuracy/quality, as well as a trade-off between ' vector and raster output. ' ' e_GDIPlus rasterizer can be used to render the page ' using Windows GDI+, whereas e_BuiltIn rasterizer can ' be used to render bitmaps using platform-independent ' graphics engine (in this case images are always converted ' to bitmap prior to printing). pdfdraw.SetRasterizerType(PDFRasterizer.Type.e_GDIPlus) ' You can uncomment the following lines in order to use ' built-in, platform-independent rasterizer instead of GDI+. ' pdfdraw.SetRasterizerType(PDFRasterizer.Type.e_BuiltIn) ' pdfdraw.SetDPI(200) End Sub Private Shared Function GetDeviceCaps(ByVal hdc As IntPtr, ByVal nIndex As Integer) As Integer End Function Private Const PHYSICALOFFSETX As Integer = 112 Private Const PHYSICALOFFSETY As Integer = 113 Private Sub OnPrintPDFPage(ByVal sender As System.Object, ByVal ev As System.Drawing.Printing.PrintPageEventArgs) Handles print_doc.PrintPage Dim gr As Graphics = ev.Graphics gr.PageUnit = GraphicsUnit.Inch Dim rectPage As Rectangle = ev.PageBounds ' print without margins ' Rectangle rectPage = ev.MarginBounds ' print using margins Dim left As Double Dim right As Double Dim top As Double Dim bottom As Double left = rectPage.Left / 100 right = rectPage.Right / 100 top = rectPage.Top / 100 bottom = rectPage.Bottom / 100 ' The above page dimensions are in inches. We need to convert ' the page dimensions to PDF units (or points). One point is ' 1/72 of an inch. Dim rect As PDFTRON.PDF.Rect = New Rect(left * 72, bottom * 72, right * 72, top * 72) Dim doc As PDFDoc = GetPDFDoc() doc.Lock() Try If print_page_itr.HasNext() Then pdfdraw.DrawInRect(print_page_itr.Current, gr, rect) ' Move to the next page, or finish printing print_page_itr.Next() ev.HasMorePages = print_page_itr.HasNext() Else ev.HasMorePages = False End If Catch ex As Exception MessageBox.Show("Printing Error: " + ex.ToString) End Try doc.Unlock() End Sub End Class