Skip to content

Instantly share code, notes, and snippets.

@PhilMurwin
Last active May 23, 2025 15:00
Show Gist options
  • Save PhilMurwin/4dfaf5151548e03f19ea4f1c0c306691 to your computer and use it in GitHub Desktop.
Save PhilMurwin/4dfaf5151548e03f19ea4f1c0c306691 to your computer and use it in GitHub Desktop.
Script to convert a PDF to a PNG using imagemagick and ghostscript
function Command-Exists {
param($command)
$oldPreference = $ErrorActionPreference
$ErrorActionPreference = 'SilentlyContinue'
$exists = Get-Command $command -ErrorAction SilentlyContinue
$ErrorActionPreference = $oldPreference
return $exists -ne $null
}
function Check-ImageMagick {
if (-not (Command-Exists 'magick')) {
Write-Host "❌ ImageMagick is not installed or not in PATH. Please install it from https://imagemagick.org/script/download.php"
return $false
}
return $true
}
function Check-Ghostscript {
if (-not (Command-Exists 'gswin64c')) {
Write-Host "❌ Ghostscript 64-bit is not installed or not in PATH. Please install it from https://ghostscript.com/releases/gsdnld.html"
return $false
}
return $true
}
function ConvertPDFtoPNG() {
#Check for required software
$imagemagickInstalled = Check-ImageMagick
$ghostscriptInstalled = Check-Ghostscript
# Exit if either dependency is missing
if (-not $imagemagickInstalled -or -not $ghostscriptInstalled) {
Write-Host "`nPlease install the missing dependencies and restart Powershell." -ForegroundColor Red
exit 1
}
# Change to the folder containing ImageMagick if not in PATH
# $imageMagickPath = "C:\Program Files\ImageMagick-7.0.10-Q16-HDRI" # Update to your install path
# $env:Path += ";$imageMagickPath"
# Set output folder (optional: uncomment to use a subfolder for PNGs)
$outputFolder = "$PWD\ConvertedPNGs"
if (!(Test-Path $outputFolder)) { New-Item -ItemType Directory -Path $outputFolder }
# Loop through all PDFs in the current folder
Get-ChildItem -Filter "*.pdf" | ForEach-Object {
$pdfPath = $_.FullName
$pdfName = $_.BaseName
# Set output pattern for PNGs (one PNG per page)
$outputPattern = "$outputFolder\$pdfName" + "_page_%d.png"
# Run ImageMagick's convert command
Write-Host "Processing: $pdfName.pdf..."
magick convert -density 300 $pdfPath $outputPattern
if ($?) {
Write-Host "✅ Successfully converted $pdfPath.pdf to PNGs in $outputFolder"
} else {
Write-Host "❌ Failed to convert $pdfPath.pdf" -ForegroundColor Red
}
}
}
# Short alias function
function pdf2png {
ConvertPDFtoPNG
}
function makepng {
ConvertPDFtoPNG
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment