<#
jsPDFt.ps1
Concatenate PDFs in sub-folders
#>
Function Get-Folder {
Add-Type -AssemblyName System.Windows.Forms
$FolderBrowser = New-Object System.Windows.Forms.FolderBrowserDialog
[void]$FolderBrowser.ShowDialog()
$temp = $FolderBrowser.SelectedPath
If($temp -eq '') {Exit}
If(-Not $temp.EndsWith('\')) {$temp = $temp + '\'}
Return $temp
}
Function Get-PDF {
Param(
[String]$folder,
[string]$source,
[string]$dest,
[string]$command
)
If(-Not $folder.EndsWith('\')) {$folder = $folder + '\'}
# If there are any PDFs in the folder then execute the concatenation
If(@(Get-ChildItem -Path ($folder + '*') -Include *.pdf -File).Count -gt 0) {
Write-Host 'Folder:' $folder -BackgroundColor Black -ForegroundColor Yellow
# Create output file name
If((Split-Path -Path $folder -Leaf).EndsWith('\')) { # Input was root folder
$outFile = $dest + '\' + $source.Substring(0, 1) + '.pdf'
} else {
$outFile = $dest + $folder.Replace($source, "") + '\' + (Split-Path -Path $folder -Leaf) + '.pdf'
}
$outFile = $outFile.Replace('\\', '\')
# Otherwise, check if output folder exists and create if necessary
If(-Not (Test-Path (Split-Path -Path $outFile))) {
New-Item (Split-Path -Path $outFile) -Type Directory | Out-Null
}
Write-Host 'File: ' $outFile -BackgroundColor Black -ForegroundColor White
# Compose argument string
$arguments = '"' + $folder + '*.pdf" cat output "' + $outFile + '"'
# Execute pdftk.exe with arguments
Start-Process -FilePath $command -Wait -ArgumentList $arguments -NoNewWindow
}
}
$console = $host.UI.RawUI
$size = $console.WindowSize
$size.Width = 80
$size.Height = 30
$console.WindowSize = $size
If($PSVersionTable.PSVersion.Major -lt 3) {
Write-Host '** Script requires at least Powershell V3 **'
} else {
Write-Host 'Choose folder with PDF files: ' -NoNewline -BackgroundColor DarkGreen -ForegroundColor White
$srcFolder = (Get-Folder)
Write-Host $srcFolder
Write-Host 'Choose output folder: ' -NoNewline -BackgroundColor DarkGreen -ForegroundColor White
Do {$dstFolder = (Get-Folder)} While($dstFolder -eq $srcFolder)
Write-Host $dstFolder
# Full path to pdftk.exe which should be in the same folder as Powershell script
$pdftk = '"' + (Split-Path $SCRIPT:MyInvocation.MyCommand.Path -Parent) + '\pdftk.exe"'
# List of sub-folders
$aFolders = @(Get-ChildItem -Path $srcFolder -Recurse -Directory | Select-Object -ExpandProperty Fullname)
for($i=0; $i -lt $aFolders.Count; $i++) {
# For each sub-folder call the routine
Get-PDF $aFolders[$i] $srcFolder $dstFolder $pdftk
}
# Finally, call routine on source folder
Get-PDF $srcFolder $srcFolder $dstFolder $pdftk
}
Write-Host ''
Write-Host 'Close window to exit ...'
cmd /c pause | out-null