Imports Microsoft.VisualBasic
Imports System.IO
Imports Microsoft.Office.Tools.Excel
Imports Microsoft.Office.Interop
'Imports Microsoft.Office.Interop.Excel
Imports Microsoft.Office.Tools.Word

'撰寫人員：吳宇澤
'撰寫日期：2012/09/30
'版本號碼：v1.1
Namespace WizardWu
    Public Class ConvertOfficeToPDF

        ''' <summary>
        ''' Word 轉 PDF
        ''' </summary>
        ''' <param name="PathAndFileName">路徑名\檔名.副檔名</param>
        ''' <remarks></remarks>
        Public Sub ConvertWordToPDF(ByVal PathAndFileName As String)
            Dim mstrResultFormPath As String = PathAndFileName
            Dim strPDFFileName As String = Path.ChangeExtension(mstrResultFormPath, ".pdf")
            Dim docApp As Object = CreateObject("Word.Application")
            Dim docDoc As Object = docApp.Documents.Open(mstrResultFormPath)
            Try
                'ExportFormat: 指定要以 PDF 還是 XPS 格式儲存文件
                docDoc.ExportAsFixedFormat(OutputFileName:=strPDFFileName, ExportFormat:=17)
            Catch ex As Exception
                Throw New Exception("轉換 Word 檔 " & PathAndFileName & " 時發生錯誤，錯誤為：" & ex.Message)
            Finally
                docApp.Documents.Close()
                docApp.Quit()
            End Try
        End Sub

        ''' <summary>
        ''' Excel 轉 PDF (可有空白 sheet)
        ''' </summary>
        ''' <param name="PathAndFileName">路徑名\檔名.副檔名</param>
        ''' <remarks></remarks>
        Public Sub ConvertExcelToPDF(ByVal PathAndFileName As String)
            'Dim ws As Excel.Worksheet

            Dim mstrResultFormPath As String = PathAndFileName  '例：d:\excelTestPDF.xls
            Dim strPDFFileName As String = Path.ChangeExtension(mstrResultFormPath, ".pdf")
            Dim xlsApp As Object = CreateObject("Excel.Application")
            Dim xlsWBook As Object = xlsApp.Workbooks.Open(mstrResultFormPath)
            Try
                xlsWBook.ExportAsFixedFormat(Type:=0, Filename:=strPDFFileName, IgnorePrintAreas:=False, OpenAfterPublish:=False, IncludeDocProperties:=True, Quality:=Excel.XlFixedFormatQuality.xlQualityStandard)
            Catch ex As Exception
                Throw New Exception("轉換 Excel 檔 " & PathAndFileName & " 時發生錯誤，錯誤為：" & ex.Message)
            Finally
                xlsApp.Workbooks.Close()
                xlsApp.Quit()
            End Try
        End Sub

    End Class
End Namespace

