I've written a Powershell script that converts every worksheet within an Excel-workbook to a seperate PDF-file. The code below works properly when the output PDF-file fits within one page.
When the content of the worksheet is large and should normally be saved to two pages, it attempts to fit it on one page. This results in a cell overlapping the footer. It should be on the next page.
The error message shows an error in the ExportAsFixedFormat method. This exception only shows when the output PDF should be exported across two or more pages.
Value does not fall within the expected range. (System.ArgumentException)
In an attempt to debug this, I came across the PageSetup property. I wanted to see the amount of pages that it contained so I added Write-Host $Worksheet.PageSetup.Pages to the inner loop.
Oddly, adding this Write-Host solved the issue. The content now spreads itself across multiple pages. Even weirder, while the PDF-files get created correctly, the error message is still there. I have two questions:
- How did adding a
Write-Hoststatement fix the export? - How do I get rid of the error message (without just supressing it)?
I've also played around with properties like PageSetup.FitToPagesTall (set to 2) and PageSetup.FitToPagesWide (set to 1), but this messed up the layout of the PDF-file.
$Formats = "Microsoft.Office.Interop.Excel.xlFixedFormatType" -as [type]
$Excel = New-Object -ComObject Excel.Application
$Excel.Visible = $false
$ExcelFiles = Get-ChildItem $ExcelDirectory -Filter "*.xlsx" -Recurse
foreach($ExcelFile in $ExcelFiles)
{
$Workbook = $Excel.Workbooks.Open($ExcelFile.FullName)
$Workbook.Saved = $true
foreach($Worksheet in $Workbook.Worksheets)
{
if($Worksheet.Name -eq "Voorblad")
{
continue
}
# Some algorithm to calculate the output file name.
# Not relevant for this question. Results in the variable $SheetPrettyName
$OutputPath = "$ExcelDirectory\" + $SheetPrettyName + ".pdf"
$Worksheet.ExportAsFixedFormat($Formats::xlTypePDF, $OutputPath)
}
$Excel.Workbooks.Close()
}
$Excel.Quit()