Tuesday, January 13, 2015

VB.NET - Export Excel to PDF

Imports System
Imports System.IO
Imports Microsoft.Office.Interop
Imports Microsoft.Office.Interop.Excel


    ''' <summary>
    ''' converts excel spreadsheet to PDF
    ''' </summary>
    ''' <param name="strXLFile">file path of excel spreadsheet</param>
    ''' <param name="strPDF">file path of where to save the pdf</param>
    ''' <remarks></remarks>
    Public Shared Sub ConvertToPDF(ByVal strXLFile As String, ByVal strPDF As String)

        Dim objExcel As Excel.Application
        Dim objWB As Excel.Workbook

        Try

            'Open Excel and the workbook
            objExcel = New Application
            objExcel.Visible = False
            objWB = objExcel.Workbooks.Open(strXLFile)
            objWB.ExportAsFixedFormat(XlFixedFormatType.xlTypePDF, strPDF, , , , , , False)

        Catch ex As Exception
            Throw ex
        Finally
            If objWB IsNot Nothing Then
                objWB.Close()
            End If

            NAR(objWB)

            If objExcel IsNot Nothing Then
                objExcel.Quit() ' Need to leave application open for display.
            End If

            NAR(objExcel)
            GC.Collect()
            GC.WaitForPendingFinalizers()
        End Try

    End Sub


    ''' <summary>
    ''' Used to properly clean up excel or powepoint COM objects.
    ''' </summary>
    ''' <param name="o"></param>
    ''' <remarks></remarks>
    Shared Sub NAR(ByVal o As Object)
        Try
            System.Runtime.InteropServices.Marshal.FinalReleaseComObject(o)
        Catch

        Finally
            o = Nothing
        End Try
    End Sub

No comments:

Post a Comment