Merge Multiple PDFs with PowerShell and PDFSharp

First you will need to download PDF Sharp and build with Visual Studio the solution “BuildAll-PdfSharp.sln” and then obtaining the output PdfSharp.dll and placing in same directory as script.

Takes a specified folder of PDFs and combines them into an output file. Modify sourcePath and outputPath as necessary.

$sourcePath = "<path to folder with PDFs to merge>" 
$outputPath = "<filename of final PDF>"

Add-Type -Path "$($PSScriptRoot)\PdfSharp.dll"
$pdfDestination = New-Object PdfSharp.Pdf.PdfDocument
$pdfFiles = Get-ChildItem -Path $sourcePath -Filter *.pdf
ForEach ($filename in $pdfFiles)
{
    "Adding '$($filename.Fullname)'"
    $pdfSource = [PdfSharp.Pdf.IO.PdfReader]::Open($filename.Fullname,[PdfSharp.Pdf.IO.PdfDocumentOpenMode]::Import)
    for ($i = 0; $i -lt $pdfSource.PageCount; $i++)
    {
        $pdfDestination.AddPage($pdfSource.Pages[$i])
    }

    $pdfSource.Close()
     
}

$pdfDestination.Save($outputPath)

About chentiangemalc

specializes in end-user computing technologies. disclaimer 1) use at your own risk. test any solution in your environment. if you do not understand the impact/consequences of what you're doing please stop, and ask advice from somebody who does. 2) views are my own at the time of posting and do not necessarily represent my current view or the view of my employer and family members/relatives. 3) over the years Microsoft/Citrix/VMWare have given me a few free shirts, pens, paper notebooks/etc. despite these gifts i will try to remain unbiased.
This entry was posted in Uncategorized. Bookmark the permalink.

Leave a comment