Imports system.IO
Imports System.Drawing
Imports Aspose
Imports Aspose.Pdf.Facades
Imports APServerLib
Imports System.Runtime.InteropServices

<ComClass(Nais3WordPdf.ClassId, Nais3WordPdf.InterfaceId, Nais3WordPdf.EventsId)> _
Public Class Nais3WordPdf

    Public Const ClassId As String = "57204338-1DCC-40b2-95BB-A0445048D5F3"
    Public Const InterfaceId As String = "520A01C6-01E9-485f-8151-87B556C85C64"
    Public Const EventsId As String = "6893ACB8-255C-471d-9146-FFD0DF8A694F"

    Public Sub New()
        Dim wordLicense As Words.License = New Words.License()
        wordLicense.SetLicense("Aspose.Total.lic")

        Dim pdfLicense As Pdf.License = New Pdf.License()
        pdfLicense.SetLicense("Aspose.Total.lic")
    End Sub

    Public Function printPdf(ByVal inpFilePath As String, ByVal printerName As String) As Integer
        Dim iRet As Integer = 0
        Try
            If File.Exists(inpFilePath) Then
                Dim inpPdfViewer As PdfViewer = New PdfViewer()
                inpPdfViewer.BindPdf(inpFilePath)

                inpPdfViewer.AutoResize = True
                inpPdfViewer.AutoRotate = True
                inpPdfViewer.PrintAsImage = False

                Dim printSetting As New Printing.PrinterSettings
                printSetting.PrinterName = printerName
                inpPdfViewer.PrintDocumentWithSettings(printSetting)

                inpPdfViewer.Close()

            End If

        Catch ex As Exception
            iRet = 1
        End Try

        Return iRet
    End Function

    Public Sub deleteFileByExt(ByVal delPath As String, ByVal delExt As String)
        Try
            If Directory.Exists(delPath) Then
                For Each FileName As String In System.IO.Directory.GetFiles(delPath, "*." + delExt)
                    Dim cFileInfo As New System.IO.FileInfo(FileName)

                    If (cFileInfo.Attributes And System.IO.FileAttributes.ReadOnly) = System.IO.FileAttributes.ReadOnly Then
                        cFileInfo.Attributes = System.IO.FileAttributes.Normal
                    End If

                    cFileInfo.Delete()
                Next
            End If
        Catch ex As Exception

        End Try

    End Sub

    Public Function picEdit(ByVal inpFilePath As String, ByRef outFilePath As String, ByVal shipName As String, ByVal pilotName1 As String, ByVal pilotName2 As String, ByVal pilotName3 As String) As Integer
        Dim iRet As Integer = 0
        Try
            If File.Exists(inpFilePath) Then
                Dim inpDoc As New Words.Document(inpFilePath)
                Dim docBuilder As New Words.DocumentBuilder(inpDoc)
                bookMarkEdit(inpDoc, docBuilder, "TotheMasterof", shipName)

                bookMarkEdit(inpDoc, docBuilder, "Pilot", pilotName1)
                bookMarkEdit(inpDoc, docBuilder, "SubPilot", pilotName2)
                bookMarkEdit(inpDoc, docBuilder, "ThirdPilot", pilotName3)

                If Path.GetExtension(outFilePath) = ".doc" Then
                    inpDoc.Save(outFilePath)
                Else
                    iRet = createPDF(inpDoc, outFilePath)
                End If

                inpDoc = Nothing
                docBuilder = Nothing
            Else
                iRet = 1
            End If
        Catch ex As Exception
            iRet = 2
        End Try

        Dim ps As System.Diagnostics.Process() = System.Diagnostics.Process.GetProcessesByName("WINWORD")

        For Each p As System.Diagnostics.Process In ps
            'クローズメッセージを送信する
            p.Kill()

            'プロセスが終了するまで最大10秒待機する
            p.WaitForExit(10000)
            'プロセスが終了したか確認する
            If Not p.HasExited Then
                iRet = 4
            End If
        Next

        Return iRet
    End Function


    Private Function createPDF(ByRef doc As Words.Document, ByVal outFilePath As String) As Integer
        Dim iRet As Integer = 0
        Dim strPrinterName As String = ""
        Dim results As APServerLib.ServerResult

        Dim ActivePDF As New APServerLib.ServerClass
        ActivePDF.OutputDirectory = Path.GetDirectoryName(outFilePath)
        ActivePDF.NewDocumentName = Path.GetFileName(outFilePath)
        results = CType(ActivePDF.BeginPrintToPDF(), APServerLib.ServerResult)
        If results.ServerStatus <> APServerLib.ResultStatus.Result_Success Then
            iRet = 3
            Return iRet
        End If

        Dim docFilePath As String = Path.GetDirectoryName(outFilePath) + "\" + Path.GetFileNameWithoutExtension(outFilePath) + ".doc"
        doc.Save(docFilePath)


        Dim oWORD As Microsoft.Office.Interop.Word._Application = New Microsoft.Office.Interop.Word.Application()
        oWORD.ActivePrinter = ActivePDF.NewPrinterName
        oWORD.DisplayAlerts = Microsoft.Office.Interop.Word.WdAlertLevel.wdAlertsNone
        oWORD.Visible = False
        Dim oDOC As Microsoft.Office.Interop.Word.Document = oWORD.Documents.Open(CObj(docFilePath))
        oDOC.Activate()
        oWORD.PrintOut()
        oWORD.Documents.Close()
        oWORD.Quit()
        oDOC = Nothing
        oWORD = Nothing

        results = CType(ActivePDF.EndPrintToPDF(30), APServerLib.ServerResult)
        If results.ServerStatus <> APServerLib.ResultStatus.Result_Success Then
            iRet = 3
            Return iRet
        End If

        ActivePDF = Nothing

        Return iRet
    End Function

    Private Sub bookMarkEdit(ByRef doc As Words.Document, ByRef docBuilder As Words.DocumentBuilder, ByVal name As String, ByVal destText As String)
        Dim bookmark As Words.Bookmark = doc.Range.Bookmarks(name)
        If Not bookmark Is Nothing Then

            Dim srcText As String = bookmark.Text
            Dim paddingNum As Integer
            paddingNum = LenB(srcText) - LenB(destText) + destText.Length
            'If LenB(destText) = destText.Length Then
            '    paddingNum = srcText.Length
            'Else
            'End If

            'Dim paddingNum As Integer = srcText.Length - destText.Length
            'bookmark.Text = destText.PadRight(paddingNum)
            bookmark.Text = ""
            docBuilder.MoveToBookmark(name)
            docBuilder.Font.Name = "ＭＳ 明朝"
            docBuilder.Font.Color = Color.Black
            docBuilder.Write(destText.PadRight(paddingNum))
        End If

    End Sub

    Private Function LenB(ByVal stTarget As String) As Integer
        Return System.Text.Encoding.GetEncoding("Shift_JIS").GetByteCount(stTarget)
    End Function

End Class
