Skip to content

Instantly share code, notes, and snippets.

@pleabargain
Created February 3, 2025 10:36
Show Gist options
  • Save pleabargain/369e817e4acf34d7a0be9f23f32bc1bb to your computer and use it in GitHub Desktop.
Save pleabargain/369e817e4acf34d7a0be9f23f32bc1bb to your computer and use it in GitHub Desktop.
powershell script to concatenate PDF into user selected order requires chocolatey and qpdf to be installed
# Check if qpdf is installed
$qpdfCheck = Get-Command qpdf -ErrorAction SilentlyContinue
if (-not $qpdfCheck) {
Write-Host "QPDF is not installed. Please install it using: choco install qpdf"
Write-Host "If you don't have chocolatey installed, visit https://chocolatey.org/install"
exit
}
# Get all PDF files in current directory
$pdfFiles = Get-ChildItem -Path $PWD -Filter "*.pdf"
# Check if PDFs exist
if ($pdfFiles.Count -eq 0) {
Write-Host "No PDF files found in current directory."
exit
}
# Display numbered list of PDFs
Write-Host "`nAvailable PDF files:"
$pdfDict = @{}
for ($i = 1; $i -le $pdfFiles.Count; $i++) {
$pdfDict[$i] = $pdfFiles[$i-1]
Write-Host "$i $($pdfFiles[$i-1].Name)"
}
# Get user's desired order
$validInput = $false
while (-not $validInput) {
$orderInput = Read-Host "`nEnter the numbers in desired order (comma-separated, e.g., 2,3,1)"
$orderArray = $orderInput -split ',' | ForEach-Object { $_.Trim() }
# Validate input
$validInput = $true
foreach ($num in $orderArray) {
if (-not ([int]::TryParse($num, [ref]$null)) -or [int]$num -lt 1 -or [int]$num -gt $pdfFiles.Count) {
Write-Host "Invalid input. Please use numbers between 1 and $($pdfFiles.Count)"
$validInput = $false
break
}
}
}
# Get output filename
$outputName = Read-Host "`nEnter name for combined PDF (without .pdf extension)"
$outputPath = Join-Path $PWD "$outputName.pdf"
try {
# Build qpdf command
$pdfPaths = $orderArray | ForEach-Object { $pdfDict[[int]$_].FullName }
$qpdfArgs = @("--empty", "--pages") + $pdfPaths + @("--", $outputPath)
# Execute qpdf
Write-Host "`nCombining PDFs..."
& qpdf $qpdfArgs
if ($LASTEXITCODE -eq 0) {
Write-Host "PDF combination complete!"
Write-Host "Output file: $outputPath"
# Get page count of resulting PDF
$pageCountArgs = @("--show-npages", $outputPath)
$totalPages = & qpdf $pageCountArgs
Write-Host "Total pages: $totalPages"
} else {
Write-Host "Error combining PDFs."
}
} catch {
Write-Host "An error occurred: $_"
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment