Files
Controls.DocumentViewer/DocumentViewer.vb
2026-05-05 07:57:31 +02:00

1010 lines
37 KiB
VB.net
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
Imports System.IO
Imports DevExpress
Imports DevExpress.Spreadsheet
Imports DevExpress.XtraRichEdit.Commands
Imports DevExpress.Office.Utils
Imports GdPicture14
Imports DigitalData.Modules.Logging
Imports DigitalData.Modules.Messaging
Imports DigitalData.Modules.Config
Public Class DocumentViewer
Private Enum ZoomMode
Zoom50
Zoom100
Zoom150
Zoom200
ZoomSelectedArea
ZoomFitToViewer
ZoomFitWidth
ZoomFitHeight
End Enum
Private Enum ViewerMode
GDPicture
Excel
Richtext
End Enum
Private Enum FileLoadMode
File
Stream
End Enum
Public ReadOnly Property PdfViewer As GdViewer
Get
Return MyGDPViewer
End Get
End Property
Private _logConfig As LogConfig
Private _logger As Logger
Private _Config As ConfigManager(Of Config)
Private _email As Email2
Private _ViewerMode As ViewerMode
Private _licenseKey As String = String.Empty
Private _licenseManager As New GdPicture14.LicenseManager()
Private _Search As Search
Private _Annotations As Annotations
Private _AnnotationsPending As Boolean = False
Private _ToolbarSettings As New ToolbarSettings
Private _hide_file_info_from_user As Boolean = False
Private _FileStream As Stream
Private _FilePath As String
Private _FileInfo As FileInfo
Private _FileLoadMode As FileLoadMode = FileLoadMode.File
Private _ViewOverride As String = ""
' List of all created temp files when converting msg files
Private _TempFiles As New List(Of String)
Private Sub DocumentViewer_Load(sender As Object, e As EventArgs) Handles Me.Load
' Ensure search is initialized once the control (and GdViewer) exists
EnsureSearchInitialized()
UpdateMainUi()
UpdateNoFileSelectedLabel(FileLoaded)
End Sub
Private Sub DocumentViewer_FileLoadedChanged(ByVal sender As Object, ByVal isLoaded As Boolean) Handles Me.FileLoadedChanged
UpdateNoFileSelectedLabel(isLoaded)
End Sub
Private Sub UpdateNoFileSelectedLabel(ByVal isLoaded As Boolean)
If lblNoFileSelected IsNot Nothing Then
lblNoFileSelected.Visible = Not isLoaded
End If
End Sub
'hallo
Public Class ToolbarSettings
Public Property ShowPrintButton As Boolean = True
Public Property ShowFitWidthButton As Boolean = True
Public Property ShowFitPageButton As Boolean = True
Public Property ShowZoomButton As Boolean = True
Public Property ShowRotateButton As Boolean = True
Public Property ShowFlipButton As Boolean = True
Public Property ShowSearchButton As Boolean = True
Public Property ShowSettingButton As Boolean = True
End Class
Private _fileLoaded As Boolean = False
Public Event FileLoadedChanged(ByVal sender As Object, ByVal isLoaded As Boolean)
Public Property FileLoaded As Boolean
Get
Return _fileLoaded
End Get
Set(ByVal value As Boolean)
If _fileLoaded = value Then
Return
End If
_fileLoaded = value
RaiseEvent FileLoadedChanged(Me, _fileLoaded)
End Set
End Property
Public Property Viewer_ForceTemporaryMode As Boolean = False
Public ReadOnly Property AnnotationsSaved As Boolean
Get
Return Not _AnnotationsPending
End Get
End Property
''' <summary>
''' Initialize the Viewer
''' </summary>
''' <param name="pLogConfig">A LogConfig object</param>
''' <param name="pLicenseKey">The GDPicture.NET License Key</param>
Public Function Init(pLogConfig As LogConfig, pLicenseKey As String, Optional pToolbarSettings As ToolbarSettings = Nothing) As Boolean
_logConfig = pLogConfig
_logger = pLogConfig.GetLogger()
If pToolbarSettings Is Nothing Then
pToolbarSettings = New ToolbarSettings
End If
Try
_email = New Email2(pLogConfig)
If pLicenseKey = String.Empty Then
_logger.Warn("License key was not provided during init-process!")
Return False
End If
_licenseKey = pLicenseKey
_licenseManager.RegisterKEY(_licenseKey)
_Annotations = New Annotations(pLogConfig)
' Defer creating Search until GdViewer is ready
EnsureSearchInitialized()
_ToolbarSettings = pToolbarSettings
Dim oConfigPath = ConfigPath()
_Config = New ConfigManager(Of Config)(pLogConfig, oConfigPath)
Return True
Catch ex As Exception
_logger.Error(ex)
Return False
End Try
End Function
' Create the Search helper only when both the log config and the GdViewer control exist
Private Sub EnsureSearchInitialized()
Try
If _Search Is Nothing AndAlso _logConfig IsNot Nothing AndAlso MyGDPViewer IsNot Nothing Then
_Search = New Search(_logConfig, MyGDPViewer)
End If
Catch ex As Exception
_logger?.Error(ex)
End Try
End Sub
''' <summary>
''' Load a file from a path and display it
''' </summary>
Public Sub LoadFile_FromPath(FilePath As String)
FileLoaded = False
If _licenseKey = String.Empty Then
_logger.Warn("License key was not provided. File {0} not loaded.", FilePath)
Exit Sub
End If
If FilePath Is Nothing OrElse FilePath.Trim().Length = 0 Then
_logger.Warn("FilePath was not provided. File not loaded.")
Exit Sub
End If
_FilePath = FilePath
_FileLoadMode = FileLoadMode.File
_FileInfo = New FileInfo(FilePath)
_logger.Info("Loading file [{0}] from Filesystem", FilePath)
SetViewerMode(_FileInfo.Extension)
FileLoaded = DoLoadFile(FilePath)
UpdateMainUi()
End Sub
''' <summary>
''' Load a file from a stream and display it
''' </summary>
Public Sub LoadFile_FromStream(FileName As String, Stream As Stream)
FileLoaded = False
Dim oExtension As String = FileName.Substring(FileName.LastIndexOf("."))
_FileStream = Stream
_FileLoadMode = FileLoadMode.Stream
_logger.Info("Loading file [{0}] from Stream", FileName)
FileLoaded = DoLoadFileExtension(Stream, oExtension)
SetViewerMode(oExtension)
UpdateMainUi()
End Sub
''' <summary>
''' Terminate Viewer, freeing up resources and deleting temp files
''' </summary>
Public Sub Done()
Try
_logger.Debug("Done: Deleting Temp Files")
DeleteTempFiles()
_logger.Debug("Done: Closing Documents")
FreeFile()
_logger.Debug("Done: Triggering GC")
GC.Collect()
Catch ex As Exception
_logger.Warn("Error while cleaning up DocumentViewer")
_logger.Error(ex)
End Try
End Sub
Public Function AddAnnotation(pText As String) As Boolean
Dim oFontStyle = FontStyle.Regular
Dim oFontColor = Color.Black
Dim oFontFamily = "Arial"
Dim oFontSize = 8
Dim oBorderColor = Color.Red
Dim oBackColor = Color.LightYellow
Dim oOpacity = 1.0F
Dim oRotation = 0.0F
MyGDPViewer.AddTextAnnotationInteractive(pText, oFontColor, oFontFamily, oFontStyle, oFontSize, Fill:=True, oBorderColor, oBackColor, oOpacity, oRotation)
_AnnotationsPending = True
Return True
End Function
Public Function Save() As Boolean
Dim oSaveResult As GdPictureStatus = GdPictureStatus.OK
If MyGDPViewer.BurnAnnotationsToPage(True, False) = GdPictureStatus.OK Then
If _FileLoadMode = FileLoadMode.Stream Then
oSaveResult = MyGDPViewer.SaveDocumentToPDF(_FileStream)
Else
oSaveResult = MyGDPViewer.SaveDocumentToPDF(_FilePath)
End If
End If
If oSaveResult = GdPictureStatus.OK Then
_AnnotationsPending = False
Return True
Else
Return False
End If
End Function
Public Sub CloseDocument()
Try
' Null-sicher schließen
If MyGDPViewer IsNot Nothing Then
Try
MyGDPViewer.CloseDocument()
Catch exInner As Exception
_logger?.Warn("Fehler beim Schließen von GdViewer")
_logger?.Error(exInner)
End Try
Else
_logger?.Debug("CloseDocument: GdViewer ist Nothing nichts zu schließen")
End If
_FileInfo = Nothing
_FilePath = Nothing
_FileStream = Nothing
FileLoaded = False
UpdateMainUi()
Catch ex As Exception
_logger.Error(ex)
FileLoaded = False
End Try
End Sub
''' <summary>
''' Configures the viewer to hide the file path to the end-user.
''' </summary>
''' <param name="ViewOnly">
''' True means that all file info should be hidden from the end-user
''' False means the end user may see the filepath or other info about the file
''' </param>
Public Sub SetViewOnly(ViewOnly As Boolean)
If ViewOnly Then
buttonPrint.Visibility = XtraBars.BarItemVisibility.Never
Else
buttonPrint.Visibility = XtraBars.BarItemVisibility.Always
End If
_hide_file_info_from_user = ViewOnly
End Sub
Public Sub SetAllowAnnotations(AllowAnnotations As Boolean)
End Sub
''' <summary>
''' DEPRECATED: Use SetViewOnly
''' </summary>
Public Sub RightViewOnly(ViewOnly As Boolean)
SetViewOnly(ViewOnly)
End Sub
''' <summary>
''' DEPRECATED: Use SetViewOnly
''' </summary>
Public Sub RightOnlyView(ViewOnly As Boolean)
SetViewOnly(ViewOnly)
End Sub
#Region "Form Events"
Private Sub btnFitWidth_Click(ByVal sender As Object, ByVal e As EventArgs) Handles buttonFitWidth.ItemClick
FitToWidth()
_Config.Config.PageFit = Config.PageFitSetting.FitWidth
_Config.Save()
End Sub
Private Sub btnFitPage_Click(ByVal sender As Object, ByVal e As EventArgs) Handles buttonFitPage.ItemClick
FitToPage()
_Config.Config.PageFit = Config.PageFitSetting.FitPage
_Config.Save()
End Sub
Private Sub btnOpen_Click(sender As Object, e As EventArgs)
FitToWidth()
MyGDPViewer.DocumentAlignment = ViewerDocumentAlignment.DocumentAlignmentTopCenter
If OpenFileDialog.ShowDialog() = DialogResult.OK Then
MyGDPViewer.DisplayFromFile(OpenFileDialog.FileName)
End If
ShowGdViewer()
MyGDPViewer.Focus()
UpdateMainUi()
End Sub
Private Sub BtnFirstPage_Click(ByVal sender As System.Object, ByVal e As EventArgs) Handles buttonFirstPage.ItemClick
MyGDPViewer.DisplayFirstPage()
End Sub
Private Sub BtnPreviousPage_Click(ByVal sender As System.Object, ByVal e As EventArgs) Handles buttonPrevPage.ItemClick
MyGDPViewer.DisplayPreviousPage()
End Sub
Private Sub BtnNextPage_Click(ByVal sender As System.Object, ByVal e As EventArgs) Handles buttonNextPage.ItemClick
MyGDPViewer.DisplayNextPage()
End Sub
Private Sub BtnLastPage_Click(ByVal sender As System.Object, ByVal e As EventArgs) Handles buttonLastPage.ItemClick
MyGDPViewer.DisplayLastPage()
End Sub
Private Sub TbCurrentPage_Leave(ByVal sender As System.Object, ByVal e As EventArgs) Handles txtCurrentPage.EditValueChanged
Dim page As Integer = 0
If Integer.TryParse(txtCurrentPage.EditValue, page) Then
If page > 0 And page <= MyGDPViewer.PageCount Then
MyGDPViewer.DisplayPage(page)
UpdateaNavigationToolbar()
End If
End If
End Sub
Private Sub GdViewer1_PageChanged() Handles MyGDPViewer.PageChanged
UpdateaNavigationToolbar()
End Sub
Private Sub GdViewer1_AfterZoomChange() Handles MyGDPViewer.AfterZoomChange
UpdateaNavigationToolbar()
If MyGDPViewer.MouseMode = ViewerMouseMode.MouseModeAreaZooming Then
MyGDPViewer.MouseMode = ViewerMouseMode.MouseModePan
End If
End Sub
Private Sub btnZoomOut_Click(sender As Object, e As EventArgs) Handles buttonZoomOut.ItemClick
MyGDPViewer.ZoomOUT()
End Sub
Private Sub btnZoomIn_Click(sender As Object, e As EventArgs) Handles buttonZoomIn.ItemClick
MyGDPViewer.ZoomIN()
End Sub
Private Sub btnPrint_Click(sender As Object, e As EventArgs) Handles buttonPrint.ItemClick
If MyGDPViewer.PageCount = 0 Then
Return
End If
MyGDPViewer.PrintDialog()
End Sub
Private Sub BtnRotateLeft_Click(sender As Object, e As EventArgs) Handles buttonRotateLeft.ItemClick
MyGDPViewer.Rotate(RotateFlipType.Rotate270FlipNone)
End Sub
Private Sub BtnRotateRight_Click(sender As Object, e As EventArgs) Handles buttonRotateRight.ItemClick
MyGDPViewer.Rotate(RotateFlipType.Rotate90FlipNone)
End Sub
Private Sub btnFlipX_Click(sender As Object, e As EventArgs) Handles buttonFlipX.ItemClick
MyGDPViewer.Rotate(RotateFlipType.RotateNoneFlipX)
End Sub
Private Sub btnFlipY_Click(sender As Object, e As EventArgs) Handles buttonFlipY.ItemClick
MyGDPViewer.Rotate(RotateFlipType.RotateNoneFlipY)
End Sub
Private Sub GdViewer1_TransferEnded(ByVal status As GdPictureStatus, ByVal download As System.Boolean) Handles MyGDPViewer.TransferEnded
MyGDPViewer.Focus()
UpdateMainUi()
End Sub
Private Sub AddSearchRegion(ByVal occurence As Integer, ByVal leftCoordinate As Single, ByVal topCoordinate As Single, ByVal regionWidth As Single, ByVal regionheight As Single, ByVal ensureVisibility As Boolean)
Dim searchRegion As Integer = MyGDPViewer.AddRegionInches("SearchResult" & occurence, leftCoordinate, topCoordinate, regionWidth, regionheight, ForegroundMixMode.ForegroundMixModeMASKPEN, Color.Yellow)
MyGDPViewer.SetRegionEditable(searchRegion, False)
If ensureVisibility Then
MyGDPViewer.EnsureRegionVisibility(searchRegion)
End If
End Sub
Private Sub BtnSettings_Click(ByVal sender As Object, ByVal e As EventArgs) Handles buttonSettings.ItemClick
Using frmSettings As New frmViewerSettings(MyGDPViewer)
frmSettings.ShowDialog(Me)
End Using
UpdateaNavigationToolbar()
End Sub
#End Region
#Region "Private Functions"
Private Function ConfigPath() As String
Return Path.Combine(Application.UserAppDataPath, "DocumentViewer")
End Function
Private Sub UpdateaNavigationToolbar()
Try
Dim oCurrentZoom As Double = MyGDPViewer.Zoom
Dim oCurrentPage As Integer = MyGDPViewer.CurrentPage
Dim oPageCount As Integer = MyGDPViewer.PageCount
txtCurrentPage.EditValue = oCurrentPage
labelPageCount.Caption = $"/ {oPageCount}"
If oCurrentPage = oPageCount Then
buttonLastPage.Enabled = False
buttonNextPage.Enabled = False
buttonPrevPage.Enabled = True
buttonFirstPage.Enabled = True
ElseIf oCurrentPage = 1 Then
buttonPrevPage.Enabled = False
buttonFirstPage.Enabled = False
buttonLastPage.Enabled = True
buttonNextPage.Enabled = True
Else
buttonPrevPage.Enabled = True
buttonFirstPage.Enabled = True
buttonLastPage.Enabled = True
buttonNextPage.Enabled = True
End If
Catch ex As Exception
_logger.Error(ex)
End Try
End Sub
Public Sub DeleteTempFiles()
For Each oFile In _TempFiles
Try
_logger.Debug("Deleting temp file [{0}]", oFile)
File.Delete(oFile)
Catch ex As Exception
_logger.Warn("Could not delete temp file [{0}]", oFile)
End Try
Next
End Sub
Private Sub SetViewerMode(Extension As String)
If _ViewOverride = "Richtext" Then
_ViewerMode = ViewerMode.Richtext
Else
Select Case Extension.ToUpper
Case "CSV"
_ViewerMode = ViewerMode.Excel
Case ".EML", ".DOC", ".DOCX", ".ODT", ".RTF", ".TXT"
_ViewerMode = ViewerMode.Richtext
Case Else
_ViewerMode = ViewerMode.GDPicture
End Select
End If
End Sub
Private Sub FreeFile()
Try
If Len(_FilePath) = 0 OrElse _FileInfo Is Nothing Then
Exit Sub
End If
Dim oExtension As String = _FileInfo.Extension.ToUpper
Select Case _ViewerMode
Case ViewerMode.Excel
_logger.Debug("Closing Excel Editor")
SpreadsheetControl1.CreateNewDocument()
Case Else
_logger.Debug("Closing GDPicture Viewer")
MyGDPViewer.CloseDocument()
End Select
Catch ex As Exception
_logger.Warn($"Unexpected error in FreeFile: {ex.Message}")
End Try
End Sub
'Private Function DoLoadFile(FilePath As String, Optional ViewOverride As String = "") As Boolean
' Try
' lblInfo.Visible = False
' Dim oFileInfo = New FileInfo(FilePath)
' Dim oExtension As String = oFileInfo.Extension.ToUpper
' lbFileNotLoaded.Visible = False
' SpreadsheetControl1.Visible = False
' RichEditControl1.Visible = False
' SpreadsheetControl1.Dock = DockStyle.None
' RichEditControl1.Dock = DockStyle.None
' Dim override_Spreadsheet As Boolean = False
' If oExtension.ToLower = ".xlsx" Then
' If oFileInfo.Length > 15000 Then
' _logger.Info("Override")
' override_Spreadsheet = True
' End If
' End If
' If ViewOverride = "Richtext" Then
' RichEditControl1.LoadDocument(FilePath, GetDocumentFormat(oExtension))
' RichEditControl1.Visible = True
' GdViewer.Visible = False
' RichEditControl1.Dock = DockStyle.Fill
' _ViewOverride = "Richtext"
' _ViewerMode = ViewerMode.Richtext
' lblInfo.Visible = True
' lblInfo.Text = "This docx-file contains a generic error and will be displayed in a reduced viewer. Please try to open the file in WORD"
' ElseIf override_Spreadsheet = True Then
' Dim oFormat = GetSpreadsheetFormat(oExtension)
' SpreadsheetControl1.LoadDocument(FilePath, oFormat)
' Dim oRange = SpreadsheetControl1.ActiveWorksheet.GetUsedRange()
' oRange.AutoFitColumns()
' SpreadsheetControl1.Visible = True
' GdViewer.Visible = False
' SpreadsheetControl1.Dock = DockStyle.Fill
' Else
' _ViewOverride = ""
' Select Case oExtension.ToUpper
' Case ".CSV"
' Dim oFormat = GetSpreadsheetFormat(oExtension)
' SpreadsheetControl1.LoadDocument(FilePath, oFormat)
' Dim oRange = SpreadsheetControl1.ActiveWorksheet.GetUsedRange()
' oRange.AutoFitColumns()
' SpreadsheetControl1.Visible = True
' GdViewer.Visible = False
' SpreadsheetControl1.Dock = DockStyle.Fill
' 'Case ".EML", ".DOC", ".DOCX", ".ODT", ".RTF", ".TXT"
' ' RichEditControl1.LoadDocument(FilePath, GetDocumentFormat(oExtension))
' ' RichEditControl1.Visible = True
' ' GdViewer.Visible = False
' ' RichEditControl1.Dock = DockStyle.Fill
' Case Else
' Select Case oExtension.ToUpper
' Case ".EML", ".DOC", ".DOCX", ".XLS", ".XLSX", ".ODT", ".RTF", ".TXT"
' GdViewer.ForceTemporaryMode = False
' End Select
' GdViewer.ZoomMode = ViewerZoomMode.ZoomModeWidthViewer
' GdViewer.DocumentAlignment = ViewerDocumentAlignment.DocumentAlignmentTopCenter
' If Viewer_ForceTemporaryMode = True Then
' GdViewer.ForceTemporaryMode = True
' End If
' GdViewer.AnnotationDropShadow = True
' GdViewer.BackColor = Color.White
' Dim oGDPState As GdPicture14.GdPictureStatus = GdViewer.DisplayFromFile(FilePath)
' If oGDPState <> GdPictureStatus.OK Then
' _logger.Warn($"GdPictureStatus is [{oGDPState}]")
' If oExtension.ToUpper = ".DOCX" And oGDPState = GdPictureStatus.GenericError Then
' DoLoadFile(FilePath, "Richtext")
' Else
' Dim oFileName = IO.Path.GetFileName(FilePath)
' lbFileNotLoaded.Text = String.Format("Datei konnte nicht geladen werden:{0}{1}", vbCrLf, oFileName)
' lbFileNotLoaded.Visible = True
' End If
' Else
' If GdViewer.Visible = False Then
' GdViewer.Visible = True
' End If
' End If
' End Select
' End If
' If _ViewOverride = "Richtext" Then
' _ViewerMode = ViewerMode.Richtext
' End If
' Return True
' Catch ex As Exception
' _logger.Error(ex)
' Return False
' End Try
'End Function
Private Function DoLoadFile(FilePath As String, Optional ViewOverride As String = "") As Boolean
Try
If Not EnsureViewerReady() Then
_logger?.Warn("GdViewer control is not initialized yet. Delaying load.")
Return False
End If
Dim oFileInfo = New FileInfo(FilePath)
Dim oExtension = oFileInfo.Extension.ToUpper
' Reset UI state
HideAllViewers()
lbFileNotLoaded.Visible = False
lblInfo.Visible = False
' Determine viewer mode and load file
If ViewOverride = "Richtext" Then
Return LoadRichtextFile(FilePath, oExtension)
ElseIf oExtension = ".CSV" Or (oExtension = ".XLSX" AndAlso oFileInfo.Length > 15000) Then
Return LoadSpreadsheetFile(FilePath, oExtension)
Else
Return LoadGdPictureFile(FilePath, oExtension)
End If
Catch ex As Exception
_logger.Error(ex)
Return False
End Try
End Function
Private Sub HideAllViewers()
SpreadsheetControl1.Visible = False
SpreadsheetControl1.Dock = DockStyle.None
RichEditControl1.Visible = False
RichEditControl1.Dock = DockStyle.None
HideGdViewer()
End Sub
Private Function LoadRichtextFile(FilePath As String, Extension As String) As Boolean
Try
RichEditControl1.LoadDocument(FilePath, GetDocumentFormat(Extension))
RichEditControl1.Visible = True
RichEditControl1.Dock = DockStyle.Fill
_ViewOverride = "Richtext"
_ViewerMode = ViewerMode.Richtext
lblInfo.Visible = True
lblInfo.Text = "This docx-file contains a generic error and will be displayed in a reduced viewer. Please try to open the file in WORD"
Return True
Catch ex As Exception
_logger.Error(ex)
Return False
End Try
End Function
Private Function LoadSpreadsheetFile(FilePath As String, Extension As String) As Boolean
Try
_logger.Debug("Loading Spreadsheet: {0}", FilePath)
Dim oFormat = GetSpreadsheetFormat(Extension)
SpreadsheetControl1.LoadDocument(FilePath, oFormat)
Dim oRange = SpreadsheetControl1.ActiveWorksheet.GetUsedRange()
oRange.AutoFitColumns()
SpreadsheetControl1.Visible = True
SpreadsheetControl1.Dock = DockStyle.Fill
_ViewerMode = ViewerMode.Excel
_ViewOverride = ""
Return True
Catch ex As Exception
_logger.Error(ex)
Return False
End Try
End Function
Private Function LoadGdPictureFile(FilePath As String, Extension As String) As Boolean
Try
_logger.Debug("Loading GdPicture: {0}", FilePath)
' Set force temporary mode for specific file types
Select Case Extension
Case ".EML", ".DOC", ".DOCX", ".XLS", ".XLSX", ".ODT", ".RTF", ".TXT"
MyGDPViewer.ForceTemporaryMode = True
End Select
MyGDPViewer.DocumentAlignment = ViewerDocumentAlignment.DocumentAlignmentTopCenter
If Viewer_ForceTemporaryMode Then
MyGDPViewer.ForceTemporaryMode = True
End If
MyGDPViewer.AnnotationDropShadow = True
Dim oGDPState = MyGDPViewer.DisplayFromFile(FilePath)
If oGDPState <> GdPictureStatus.OK Then
_logger.Warn("GdPictureStatus: {0}", oGDPState)
' Fallback to Richtext for corrupted DOCX
If Extension = ".DOCX" AndAlso oGDPState = GdPictureStatus.GenericError Then
HideGdViewer()
Return LoadRichtextFile(FilePath, Extension)
Else
ShowFileNotLoadedError(FilePath)
Return False
End If
End If
ShowGdViewer()
MyGDPViewer.MouseWheelMode = ViewerMouseWheelMode.MouseWheelModeVerticalScroll
_ViewerMode = ViewerMode.GDPicture
_ViewOverride = ""
Return True
Catch ex As Exception
_logger.Error(ex)
ShowFileNotLoadedError(FilePath)
Return False
End Try
End Function
Private Sub ShowFileNotLoadedError(FilePath As String)
Dim oFileName = IO.Path.GetFileName(FilePath)
lbFileNotLoaded.Text = String.Format("Datei konnte nicht geladen werden:{0}{1}", vbCrLf, oFileName)
lbFileNotLoaded.Visible = True
HideGdViewer()
End Sub
' Ensures the embedded GdViewer control exists and is added to the visual tree
Private Function EnsureViewerReady() As Boolean
Try
' If the control field is Nothing (e.g., designer not yet created), try to lazy-create and add it
If MyGDPViewer Is Nothing Then
' Attempt to find an existing instance by name in Controls collection
Dim existing = Me.Controls.OfType(Of GdPicture14.GdViewer)().FirstOrDefault()
If existing IsNot Nothing Then
' Assign the designer field via reflection if needed, otherwise use it directly
MyGDPViewer = existing
Else
' Last resort: create a new viewer and add it
Dim viewer = New GdPicture14.GdViewer()
viewer.Dock = DockStyle.Fill
Me.Controls.Add(viewer)
MyGDPViewer = viewer
End If
End If
Return MyGDPViewer IsNot Nothing
Catch ex As Exception
_logger?.Error(ex)
Return False
End Try
End Function
Private Sub FitToPage()
If Not MyGDPViewer Is Nothing Then
MyGDPViewer.ZoomMode = ViewerZoomMode.ZoomModeFitToViewer
End If
End Sub
Private Sub FitToWidth()
If Not MyGDPViewer Is Nothing Then
MyGDPViewer.ZoomMode = ViewerZoomMode.ZoomModeWidthViewer
End If
End Sub
Private Sub ShowGdViewer()
If MyGDPViewer IsNot Nothing Then
MyGDPViewer.Dock = DockStyle.Fill
MyGDPViewer.Visible = True
FitToWidth()
End If
End Sub
Private Sub HideGdViewer()
If MyGDPViewer IsNot Nothing Then
MyGDPViewer.Visible = False
MyGDPViewer.Dock = DockStyle.None
End If
End Sub
Private Function DoLoadFileExtension(Stream As Stream, Extension As String) As Boolean
Try
SpreadsheetControl1.Visible = False
SpreadsheetControl1.Dock = DockStyle.None
Select Case Extension.ToUpper
Case ".CSV"
SpreadsheetControl1.LoadDocument(Stream, GetSpreadsheetFormat(Extension))
Dim oRange = SpreadsheetControl1.ActiveWorksheet.GetUsedRange()
oRange.AutoFitColumns()
SpreadsheetControl1.Visible = True
SpreadsheetControl1.Dock = DockStyle.Fill
Case Else
If Not MyGDPViewer Is Nothing Then
MyGDPViewer.DocumentAlignment = ViewerDocumentAlignment.DocumentAlignmentTopCenter
If Viewer_ForceTemporaryMode = True Then
MyGDPViewer.ForceTemporaryMode = True
End If
MyGDPViewer.AnnotationDropShadow = True
MyGDPViewer.DisplayFromStream(Stream)
ShowGdViewer()
End If
End Select
UpdateMainUi()
Return True
Catch ex As Exception
_logger.Error(ex)
Return False
End Try
End Function
Private Function StreamFile(Stream As Stream, Extension As String) As Boolean
Try
SpreadsheetControl1.Visible = False
SpreadsheetControl1.Dock = DockStyle.None
Select Case Extension.ToUpper
Case ".CSV"
SpreadsheetControl1.LoadDocument(Stream, GetSpreadsheetFormat(Extension))
Dim oRange = SpreadsheetControl1.ActiveWorksheet.GetUsedRange()
oRange.AutoFitColumns()
SpreadsheetControl1.Visible = True
SpreadsheetControl1.Dock = DockStyle.Fill
Case Else
MyGDPViewer.DocumentAlignment = ViewerDocumentAlignment.DocumentAlignmentTopCenter
MyGDPViewer.ForceTemporaryMode = True
MyGDPViewer.AnnotationDropShadow = True
MyGDPViewer.DisplayFromStream(Stream)
ShowGdViewer()
End Select
UpdateMainUi()
Return True
Catch ex As Exception
_logger.Error(ex)
Return False
End Try
End Function
Private Function GetSpreadsheetFormat(Extension) As Spreadsheet.DocumentFormat
Dim oFormat As Spreadsheet.DocumentFormat = Spreadsheet.DocumentFormat.Undefined
Select Case Extension.ToUpper
Case ".XLSX" : oFormat = Spreadsheet.DocumentFormat.Xlsx
Case ".XLS" : oFormat = Spreadsheet.DocumentFormat.Xls
Case ".CSV" : oFormat = Spreadsheet.DocumentFormat.Csv
End Select
Return oFormat
End Function
Private Function GetDocumentFormat(Extension) As XtraRichEdit.DocumentFormat
Dim oFormat As XtraRichEdit.DocumentFormat = XtraRichEdit.DocumentFormat.Undefined
Select Case Extension.ToUpper
Case ".EML" : oFormat = XtraRichEdit.DocumentFormat.Mht
Case ".DOC" : oFormat = XtraRichEdit.DocumentFormat.Doc
Case ".DOCX" : oFormat = XtraRichEdit.DocumentFormat.OpenXml
Case ".ODT" : oFormat = XtraRichEdit.DocumentFormat.OpenDocument
Case ".RTF" : oFormat = XtraRichEdit.DocumentFormat.Rtf
Case ".TXT" : oFormat = XtraRichEdit.DocumentFormat.PlainText
End Select
Return oFormat
End Function
Private Function ToVisibility(pBoolean As Boolean) As XtraBars.BarItemVisibility
If (pBoolean = True) Then
Return XtraBars.BarItemVisibility.Always
Else
Return XtraBars.BarItemVisibility.Never
End If
End Function
Private Sub UpdateMainUi()
Select Case _Config?.Config?.PageFit
Case Config.PageFitSetting.FitPage
FitToPage()
Case Config.PageFitSetting.FitWidth
FitToWidth()
End Select
If _FileStream Is Nothing And _FilePath Is Nothing Then
lbFileNotLoaded.Visible = False
End If
Select Case _ViewerMode
Case ViewerMode.GDPicture
ToolbarDocumentViewer.Visible = True
buttonPrint.Visibility = ToVisibility(_ToolbarSettings.ShowPrintButton)
buttonFitWidth.Visibility = ToVisibility(_ToolbarSettings.ShowFitWidthButton)
buttonFitPage.Visibility = ToVisibility(_ToolbarSettings.ShowFitPageButton)
buttonZoomIn.Visibility = ToVisibility(_ToolbarSettings.ShowZoomButton)
buttonZoomOut.Visibility = ToVisibility(_ToolbarSettings.ShowZoomButton)
buttonRotateLeft.Visibility = ToVisibility(_ToolbarSettings.ShowRotateButton)
buttonRotateRight.Visibility = ToVisibility(_ToolbarSettings.ShowRotateButton)
buttonFlipX.Visibility = ToVisibility(_ToolbarSettings.ShowFlipButton)
buttonFlipY.Visibility = ToVisibility(_ToolbarSettings.ShowFlipButton)
buttonSettings.Visibility = ToVisibility(_ToolbarSettings.ShowSettingButton)
txtSearch.Visibility = ToVisibility(_ToolbarSettings.ShowSearchButton)
btnSearch2.Visibility = ToVisibility(_ToolbarSettings.ShowSearchButton)
btnNextHighlight.Visibility = ToVisibility(_ToolbarSettings.ShowSearchButton)
btnPrevHighlight.Visibility = ToVisibility(_ToolbarSettings.ShowSearchButton)
buttonFirstPage.Visibility = ToVisibility(True)
buttonPrevPage.Visibility = ToVisibility(True)
buttonNextPage.Visibility = ToVisibility(True)
buttonLastPage.Visibility = ToVisibility(True)
txtCurrentPage.Visibility = ToVisibility(True)
Case ViewerMode.Excel
ToolbarDocumentViewer.Visible = False
buttonPrint.Visibility = ToVisibility(False)
buttonFitWidth.Visibility = ToVisibility(False)
buttonFitPage.Visibility = ToVisibility(False)
buttonZoomIn.Visibility = ToVisibility(False)
buttonZoomOut.Visibility = ToVisibility(False)
buttonRotateLeft.Visibility = ToVisibility(False)
buttonRotateRight.Visibility = ToVisibility(False)
buttonFlipX.Visibility = ToVisibility(False)
buttonFlipY.Visibility = ToVisibility(False)
buttonFirstPage.Visibility = ToVisibility(False)
buttonPrevPage.Visibility = ToVisibility(False)
buttonNextPage.Visibility = ToVisibility(False)
buttonLastPage.Visibility = ToVisibility(False)
buttonSettings.Visibility = ToVisibility(False)
txtCurrentPage.Visibility = ToVisibility(False)
txtSearch.Visibility = ToVisibility(False)
btnSearch2.Visibility = ToVisibility(False)
btnNextHighlight.Visibility = ToVisibility(False)
btnPrevHighlight.Visibility = ToVisibility(False)
Case Else
ToolbarDocumentViewer.Visible = False
End Select
End Sub
Private Sub btnSearch2_ItemClick(sender As Object, e As XtraBars.ItemClickEventArgs) Handles btnSearch2.ItemClick
EnsureSearchInitialized()
If _Search IsNot Nothing AndAlso Not String.IsNullOrEmpty(txtSearch.EditValue) Then
_Search.SearchAll(txtSearch.EditValue?.ToString)
End If
End Sub
Private Sub btnPrevHighlight_ItemClick(sender As Object, e As XtraBars.ItemClickEventArgs) Handles btnPrevHighlight.ItemClick
EnsureSearchInitialized()
_Search?.PrevHighlight()
End Sub
Private Sub btnNextHighlight_ItemClick(sender As Object, e As XtraBars.ItemClickEventArgs) Handles btnNextHighlight.ItemClick
EnsureSearchInitialized()
_Search?.NextHighlight()
End Sub
Private Sub txtSearch_EditValueChanged(sender As Object, e As EventArgs) Handles txtSearch.EditValueChanged
If String.IsNullOrEmpty(txtSearch.EditValue) Then
btnPrevHighlight.Enabled = False
btnNextHighlight.Enabled = False
Else
btnPrevHighlight.Enabled = True
btnNextHighlight.Enabled = True
End If
End Sub
#End Region
End Class