Convert Excel file to PDF with PowerShell

Published:  

powershell excel


Introducing a PowerShell script that converts an Excel file to PDF format and saves it.

Environment

  • Windows 10
  • PowerShell 5.1

Convert Excel file to PDF

Here is the script.
Execute by passing the path of the Excel file as a parameter. A PDF file is created in the same folder as the Excel file.

param(
    # Excel file path
    [parameter(mandatory)][string]$filepath
)

$fileitem = Get-Item $filepath

try {
    $excel = New-Object -ComObject Excel.Application
    $excel.Visible = $false
    $excel.DisplayAlerts = $false

    $wb = $excel.Workbooks.Open($fileitem.FullName)

    # Generate path of save destination PDF file
    $pdfpath = $fileitem.DirectoryName + "\" + $fileitem.BaseName + ".pdf"

    # Save as PDF
    $wb.ExportAsFixedFormat([Microsoft.Office.Interop.Excel.XlFixedFormatType]::xlTypePDF, $pdfpath)

    $wb.Close()

    $excel.Quit()
}
finally {
    # Release objects
    $sheet, $wb, $excel | ForEach-Object {
        if ($_ -ne $null) {
            [void][System.Runtime.Interopservices.Marshal]::ReleaseComObject($_)
        }
    }
}

By using the ExportAsFixedFormat method, you can save an Excel workbook in PDF format. Specify the save format in the first argument, and specify the file name of the save destination in the second argument.

The ExportAsFixedFormat method can save in XPS format in addition to PDF. If you want to know about other options such as page specification, please refer to here.

References

Workbook.ExportAsFixedFormat method (Excel)



Related Posts