Imports System.IO
Imports DigitalData.Modules.Interfaces.Exceptions
Imports DigitalData.Modules.Logging
Imports GdPicture14

Public Class PDFConverter
    Private ReadOnly _LogConfig As LogConfig
    Private ReadOnly _Logger As Logger

    Public Sub New(pLogConfig As LogConfig)
        _LogConfig = pLogConfig
        _Logger = pLogConfig.GetLogger()
    End Sub

    Public Function ConvertPDFADocumentToPDFDocument(pFilePath As String, pNewFilePath As String) As Boolean
        Try
            Using oGdPicturePDF As New GdPicturePDF()
                Using oGdPicturePDFDestination As New GdPicturePDF()

                    ' Load the source file into memory
                    If oGdPicturePDF.LoadFromFile(pFilePath, True) <> GdPictureStatus.OK Then
                        Throw New ApplicationException("File could not be loaded!")
                    End If

                    ' Create a new pdf file
                    If oGdPicturePDFDestination.NewPDF() <> GdPictureStatus.OK Then
                        Throw New ApplicationException("New Pdf could not be created!")
                    End If

                    ' Copy all pages from the source into the new pdf
                    If oGdPicturePDFDestination.ClonePages(oGdPicturePDF, "*") <> GdPictureStatus.OK Then
                        Throw New ApplicationException("Document could not be copied into new pdf!")
                    End If

                    ' Close the source document
                    If oGdPicturePDF.CloseDocument() <> GdPictureStatus.OK Then
                        Throw New ApplicationException("Source document could not be closed!")
                    End If

                    ' Set the file path
                    Dim oFinalFilePath = pFilePath
                    If Not String.IsNullOrWhiteSpace(pNewFilePath) Then
                        oFinalFilePath = pNewFilePath
                    End If

                    ' Save the file to disk
                    If oGdPicturePDFDestination.SaveToFile(oFinalFilePath) <> GdPictureStatus.OK Then
                        Throw New ApplicationException("New document could not be saved to disk!")
                    End If

                    If oGdPicturePDFDestination.CloseDocument() <> GdPictureStatus.OK Then
                        Throw New ApplicationException("Destination document could not be closed!")
                    End If

                End Using
            End Using

            Return True
        Catch ex As Exception
            _Logger.Error(ex)
            Return False
        End Try


    End Function


End Class
