PowerShell: Batch Convert Every Excel File in a Folder to PDF

Advertisement
Batch convert every Excel file in a folder to PDF with PowerShell File Operations
Advertisement

At the end of the month I sometimes have to send ten or twenty Excel files as PDFs. Opening each one and going through Save As gets old fast, and a wide table quietly splits across two pages. Batch converters exist, but a work PC usually won’t let you install one, and uploading internal spreadsheets to a conversion website is out of the question.

So I wrote a small PowerShell tool that drives the Excel already on the PC. Pick a folder, choose one PDF per workbook or one PDF per sheet, and click a button. It can also shrink wide tables to one page across. The PDFs look exactly like the ones you get from Save As.

PowerShell tool that converts every Excel file in a folder to PDF
Two invoices, a sales table, a monthly report: four PDFs in about 6 seconds

Ways to turn Excel files into PDFs

Every method below builds the PDF from Excel’s own print settings (print area, orientation, scaling), so the result looks like Excel’s print preview. The difference is how many files you can do at once, plus whether your files leave the PC.

Method How it works Downside
Save As / Export in Excel Open each file and choose PDF Slow with many files
Microsoft Print to PDF Print to the PDF printer Still one file at a time. Splitting by sheet is manual
A VBA macro loop Write a macro that opens each file in turn Needs a macro-enabled workbook. Many companies block macros
Converter websites or apps Upload in bulk or install a batch converter Often blocked on work PCs, and the files leave your machine
PowerShell (this post) Pick a folder and click a button Needs Excel installed on the PC

Isn’t this just Save As in a loop?

Yes. Under the hood the tool calls Excel’s own PDF export once per file, so the PDFs are identical to the ones you would save by hand. What it adds is everything that tends to break when you write that loop yourself:

  • No VBA, so it runs on PCs where macros are blocked
  • Password prompts and link prompts can’t stall it
  • The hidden Excel it starts is always closed
  • One PDF per sheet, with each file named Workbook_Sheet.pdf
  • Wide tables can be fit to one page across without touching the original file

What the PDF looks like

Here is a typical invoice with formulas, borders, fill colors, plus merged cells. On the left it is open in Excel; on the right is the PDF the tool made.

The original invoice in Excel next to the PDF made by the tool
Formulas turn into their results; borders and colors print as they would on paper

Formulas (quantity times price, subtotal, tax, total) show up as their calculated values. Borders, fills, fonts, number formats stay as they are, and Excel’s gray gridlines don’t print because this workbook has them turned off for printing. Charts come through too (see the monthly report below). A PDF is a printout, so the formulas themselves are not kept.

My copy of Excel is Japanese, which is why the ribbon in these screenshots is in Japanese. The workbooks themselves are in English.

The script

Paste the whole script into a PowerShell window and press Enter. It runs in Windows PowerShell 5.1 as well as PowerShell 7. No admin rights needed.

# Convert every Excel file in a folder to PDF (PowerShell 5.1 / 7, needs Excel installed)
Add-Type -AssemblyName System.Windows.Forms, System.Drawing
[System.Windows.Forms.Application]::EnableVisualStyles()

function Add-Ctl($ctl, $x, $y, $w, $h) {
    $ctl.Location = New-Object System.Drawing.Point($x, $y)
    $ctl.Size = New-Object System.Drawing.Size($w, $h)
    $form.Controls.Add($ctl)
    return $ctl
}
function Pick-Folder($box) {
    $dlg = New-Object System.Windows.Forms.FolderBrowserDialog
    if (Test-Path -LiteralPath $box.Text) { $dlg.SelectedPath = $box.Text }
    if ($dlg.ShowDialog() -eq "OK") { $box.Text = $dlg.SelectedPath }
}
function Write-Log($msg) {
    $txtLog.AppendText($msg + "`r`n")
    [System.Windows.Forms.Application]::DoEvents()
}
function Release($obj) {
    if ($null -ne $obj) { [void][System.Runtime.InteropServices.Marshal]::ReleaseComObject($obj) }
}

# Fit wide sheets to one page across (any number of pages down)
# The workbook is closed without saving, so the original print settings stay as they were
function Set-FitWide($excel, $book) {
    $excel.PrintCommunication = $false
    $sheets = $book.Worksheets
    foreach ($ws in @($sheets)) {
        $ps = $ws.PageSetup
        # leave sheets that already use Fit To alone
        if ($ps.Zoom -ne $false) { $ps.Zoom = $false; $ps.FitToPagesWide = 1; $ps.FitToPagesTall = $false }
        Release $ps; Release $ws
    }
    Release $sheets
    $excel.PrintCommunication = $true
}

function Convert-Folder {
    $src = $txtFolder.Text.Trim().TrimEnd("\")
    if (-not (Test-Path -LiteralPath $src -PathType Container)) { Write-Log "Source folder not found"; return }
    $dest = $txtDest.Text.Trim().TrimEnd("\")
    if ($dest -eq "") { $dest = Join-Path $src "PDF" }

    $files = @(Get-ChildItem -LiteralPath $src -File -Recurse:$chkSub.Checked |
        Where-Object { $_.Extension -in ".xlsx", ".xlsm", ".xls", ".xlsb" -and $_.Name -notlike '~$*' -and
                       -not $_.FullName.StartsWith($dest + "\", [StringComparison]::OrdinalIgnoreCase) })
    if ($files.Count -eq 0) { Write-Log "No Excel files found"; return }
    Write-Log ("Converting {0} Excel files -> {1}" -f $files.Count, $dest)

    $before = @(Get-Process EXCEL -ErrorAction SilentlyContinue).Id
    $excel = New-Object -ComObject Excel.Application
    $mine = @(Get-Process EXCEL -ErrorAction SilentlyContinue | Where-Object { $before -notcontains $_.Id })
    $excel.Visible = $false
    $excel.DisplayAlerts = $false
    $excel.AutomationSecurity = 3            # never run macros (msoAutomationSecurityForceDisable)
    $ok = 0; $ng = 0
    # Open options: no link updates, read-only, blank password
    # (a protected workbook fails right away, with no prompt)
    $noLinks = 0; $readOnly = $true; $noPassword = ""
    try {
        foreach ($f in $files) {
            $sub = ($f.DirectoryName -replace ("^" + [regex]::Escape($src)), "").TrimStart("\")
            $outDir = if ($sub) { Join-Path $dest $sub } else { $dest }
            New-Item -ItemType Directory -Path $outDir -Force | Out-Null
            $base = [IO.Path]::GetFileNameWithoutExtension($f.Name)
            $book = $null
            try {
                $book = $excel.Workbooks.Open($f.FullName, $noLinks, $readOnly, [Type]::Missing, $noPassword)
                if ($chkFit.Checked) { Set-FitWide $excel $book }
                if ($radBook.Checked) {
                    $pdf = Join-Path $outDir ($base + ".pdf")
                    if ((Test-Path -LiteralPath $pdf) -and -not $chkOver.Checked) { Write-Log "SKIP $($f.Name) (PDF already exists)"; continue }
                    $book.ExportAsFixedFormat(0, $pdf)    # 0 = PDF
                    Write-Log "OK   $($f.Name) -> $(Split-Path $pdf -Leaf)"
                    $ok++
                } else {
                    foreach ($ws in @($book.Worksheets)) {
                        if ($ws.Visible -ne -1) { Write-Log "SKIP $($f.Name) [$($ws.Name)] (hidden sheet)"; Release $ws; continue }
                        $name = $base + "_" + ($ws.Name -replace '[\\/:*?"<>|]', "_")
                        $pdf = Join-Path $outDir ($name + ".pdf")
                        if ((Test-Path -LiteralPath $pdf) -and -not $chkOver.Checked) { Write-Log "SKIP $name.pdf (PDF already exists)"; Release $ws; continue }
                        try {
                            $ws.ExportAsFixedFormat(0, $pdf)
                            Write-Log "OK   $($f.Name) [$($ws.Name)] -> $name.pdf"
                            $ok++
                        } catch {
                            Write-Log "NG   $($f.Name) [$($ws.Name)]: nothing to print on this sheet?"
                            $ng++
                        }
                        Release $ws
                    }
                }
            } catch {
                Write-Log "NG   $($f.Name): $($_.Exception.Message)"
                $ng++
            } finally {
                if ($null -ne $book) { $book.Close($false); Release $book }
            }
        }
    } finally {
        $excel.Quit()
        Release $excel
        [GC]::Collect(); [GC]::WaitForPendingFinalizers()
        # If the Excel this tool started is still running after 5 seconds, end it (Excel you opened yourself is left alone)
        foreach ($p in $mine) {
            if (-not $p.WaitForExit(5000)) { Stop-Process -Id $p.Id -Force; Write-Log "Ended a leftover background Excel" }
        }
    }
    Write-Log ("Done ({0} PDFs, {1} failed)" -f $ok, $ng)
    if ($ok -gt 0) { Invoke-Item -LiteralPath $dest }
}

$form = New-Object System.Windows.Forms.Form
$form.Text = "Convert Excel files in a folder to PDF"
$form.Size = New-Object System.Drawing.Size(820, 560)
$form.StartPosition = "CenterScreen"
$form.Font = New-Object System.Drawing.Font("Segoe UI", 9)

$lbl = Add-Ctl (New-Object System.Windows.Forms.Label) 12 15 120 20; $lbl.Text = "Source folder"
$txtFolder = Add-Ctl (New-Object System.Windows.Forms.TextBox) 135 12 560 23; $txtFolder.Text = [Environment]::GetFolderPath("MyDocuments")
$btn = Add-Ctl (New-Object System.Windows.Forms.Button) 705 11 80 25; $btn.Text = "Browse..."
$btn.Add_Click({ Pick-Folder $txtFolder })
$chkSub = Add-Ctl (New-Object System.Windows.Forms.CheckBox) 135 42 300 22; $chkSub.Text = "Include subfolders"

$radBook  = Add-Ctl (New-Object System.Windows.Forms.RadioButton) 135 70 300 22; $radBook.Text  = "One PDF per workbook (all sheets)"; $radBook.Checked = $true
$radSheet = Add-Ctl (New-Object System.Windows.Forms.RadioButton) 445 70 300 22; $radSheet.Text = "One PDF per sheet"

$lbl = Add-Ctl (New-Object System.Windows.Forms.Label) 12 103 120 20; $lbl.Text = "Save PDFs to"
$txtDest = Add-Ctl (New-Object System.Windows.Forms.TextBox) 135 100 560 23
$btn = Add-Ctl (New-Object System.Windows.Forms.Button) 705 99 80 25; $btn.Text = "Browse..."
$btn.Add_Click({ Pick-Folder $txtDest })
$lbl = Add-Ctl (New-Object System.Windows.Forms.Label) 135 126 650 20; $lbl.Text = 'Leave blank to use a "PDF" folder inside the source folder'
$chkOver = Add-Ctl (New-Object System.Windows.Forms.CheckBox) 135 148 400 22; $chkOver.Text = "Overwrite PDFs that already exist"
$chkFit = Add-Ctl (New-Object System.Windows.Forms.CheckBox) 445 148 340 22; $chkFit.Text = "Fit each sheet to one page wide"

$btnRun = Add-Ctl (New-Object System.Windows.Forms.Button) 12 178 200 34; $btnRun.Text = "Convert to PDF"
$txtLog = Add-Ctl (New-Object System.Windows.Forms.TextBox) 12 222 775 285
$txtLog.Multiline = $true; $txtLog.ScrollBars = "Vertical"; $txtLog.ReadOnly = $true

$btnRun.Add_Click({
    $btnRun.Enabled = $false
    try { Convert-Folder } catch { Write-Log "Stopped: $($_.Exception.Message)" }
    $btnRun.Enabled = $true
})
[void]$form.ShowDialog()

Feel free to use and modify it.

The options

Option What it does
Source folder Starts at Documents. Browse to any folder, including a network share
Include subfolders Also converts workbooks in subfolders. PDFs are saved in the same folder layout
One PDF per workbook All visible sheets go into one PDF named after the workbook
One PDF per sheet Each sheet becomes Workbook_Sheet.pdf. Hidden sheets are skipped
Save PDFs to Blank means a "PDF" folder inside the source folder
Overwrite PDFs that already exist When unchecked, existing PDFs are skipped
Fit each sheet to one page wide Shrinks wide tables so they don’t split across pages (any number of pages down). The original file is not changed

It picks up .xlsx, .xlsm, .xls, and .xlsb files. The temporary ~$ files Excel makes while a workbook is open are skipped. Workbooks are opened read-only and closed without saving, so your originals never change.

Test run

I set up a folder the way it might look at month end: two invoices, a monthly sales table by branch (14 columns wide), plus a monthly report with a table and a chart on each department’s sheet. With One PDF per workbook, the four PDFs were done in about 6 seconds (the screenshot at the top).

Wide tables split across two pages

Left alone, the sales table breaks between November and December. Excel’s Page Break Preview shows the dashed line where the second page starts.

The wide sales table in Page Break Preview
The page breaks at the dashed line between Nov and Dec

So I checked Fit each sheet to one page wide and ran it again.

The tool with Fit each sheet to one page wide checked
Same folder, new destination, with the fit option on
The sales table as a PDF with and without the fit option
Left: unchecked, two pages. Right: checked, one page

Without the option the table came out as two pages, April to November and December to March. With it, the whole table fits on one page. The text shrinks to about 70% of its size, so if that is too small, switch the workbook to landscape first (the tool doesn’t change orientation). Sheets that already use Fit To in Page Setup are left as they are.

One PDF per department sheet

The monthly report has a Sales, Admin, and Engineering sheet, each with its own table and chart. To hand each department its own file, I converted it with One PDF per sheet.

The monthly report workbook with one sheet per department
Three sheets: Sales, Admin, Engineering
Three PDFs, one per sheet
Each sheet becomes Workbook_Sheet.pdf, chart included

That gave three files such as Monthly_report_Oct_Sales.pdf, with each chart exactly as it looks in Excel. The invoices and the sales table also became Workbook_Sheet.pdf files.

Open workbooks, password-protected files, odd sheets

In a separate run I mixed in a password-protected workbook, an old .xls file, a macro-enabled .xlsm, a staff list with one hidden sheet plus one empty sheet, and I kept Quote.xlsx open in my own Excel window.

Converting 7 Excel files -> D:\Test\PDF
OK   Old-format.xls -> Old-format.pdf
NG   Password.xlsx: 入力したパスワードが間違っています。CapsLock キーの状態に注意して、大文字と小文字が正しく使われていることを確認してください。
OK   Quote.xlsx -> Quote.pdf
OK   Sales_Oct.xlsx -> Sales_Oct.pdf
OK   Staff.xlsx -> Staff.pdf
OK   Expenses_Nov.xlsx -> Expenses_Nov.pdf
OK   Macro.xlsm -> Macro.pdf
Done (6 PDFs, 1 failed)

The open quote converted fine and my Excel window was left alone. The password-protected workbook failed without ever showing a password prompt, so the run kept going. Its error text is in Japanese only because my copy of Excel is Japanese. In per-sheet mode the hidden sheet was skipped and the empty sheet failed (more on that below). I also logged the Excel processes every 0.3 seconds: a second Excel appeared while converting and was gone when it finished. Windows PowerShell 5.1 and PowerShell 7 gave the same PDFs.

Things that tripped me up

Keeping Excel from lingering in the background

When PowerShell automates Excel, EXCEL.EXE often stays in Task Manager after the script ends. You can’t see it, but it holds memory and can keep files locked. The script releases each workbook with ReleaseComObject, calls Quit, and then runs garbage collection. If the Excel it started is still alive five seconds later, it ends that one process. Any Excel you opened yourself was already running before the tool started, so it is never touched.

When I first added the fit option, Excel outlived those five seconds every time and had to be ended. The new code had reached Excel itself plus the sheet list through the workbook without releasing them. Once it released those too, Excel quit in under a second in both PowerShell 5.1 and 7.

Prompts nobody can see

A hidden Excel that shows “Enter password” or “Update links?” will wait forever. The script opens each workbook with links not updated, read-only, and with an empty password. Protected workbooks fail with a logged error instead of hanging. Macros are disabled through AutomationSecurity, so workbook-open macros never run.

Empty sheets can’t become PDFs

In per-sheet mode, Excel refuses to export a sheet with nothing to print. The tool logs it as a failure and moves on. In per-workbook mode the empty sheet is simply left out of the PDF.

Related posts

If you copy text out of the resulting PDFs, removing line breaks from PDF text fixes the broken lines without any extra software. To rename a batch of files before converting, see bulk renaming files with a one-line undo.

Summary

  • PowerShell can drive the Excel already installed to convert a whole folder to PDF. The output matches Save As
  • Choose one PDF per workbook or per sheet, and fit wide tables to one page across
  • No macros, no stalled prompts, no Excel left running in the background

References

Comments

Copied title and URL