Skip to content

Instantly share code, notes, and snippets.

@bbbco
Last active December 10, 2023 03:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bbbco/992614241a940f1fbd9b6bd1dbe831e5 to your computer and use it in GitHub Desktop.
Save bbbco/992614241a940f1fbd9b6bd1dbe831e5 to your computer and use it in GitHub Desktop.
# Converts PDF file passed into script into PNG files. Requires Ghostscript to be installed.
# Based on https://github.com/DeadExecutive/pdf_to_png/blob/main/PDF_To_PNG.ps1
#
# To enable drag and drop files, create a desktop shortcut with this command:
# powershell.exe -noprofile -noexit -File "C:\Path\To\ConvertPDFToPNGs.ps1"
# Input PDF path as an argument
param (
[Parameter(ValueFromRemainingArguments=$true)]
$pdfPath
)
# Output directory for PNG files
$outputDirectory = Join-Path $env:USERPROFILE 'Documents'
# Check if a PDF path is provided
if (-not $pdfPath) {
Write-Host "Please drag a PDF onto this script." -ForegroundColor Yellow
Exit
}
# Extract the name of the pdf file without extension
$pdfName = [System.IO.Path]::GetFileNameWithoutExtension($pdfPath)
# Create the directory for PNG files with name of PDF
$finalOutputDirectory = "$outputDirectory\$pdfName"
$gsPath = Join-Path $env:ProgramFiles 'gs\gs10.02.1\bin\gswin64c.exe'
# Check if Ghostscript is installed
if (-Not (Test-Path ($gsPath))) {
Write-Host "Ghostscript is not installed or could not be found on this system."
Write-Host "Please install Ghostscript and try again."
Exit
}
# Ensure the output directory exists
if (-Not (Test-Path -Path $finalOutputDirectory)) {
New-Item -ItemType Directory -Force -Path $finalOutputDirectory | Out-Null
}
# Ghostscript commandline args
$arguments = @(
"-q", # Quiet mode
"-dSAFER", # Enables a safer mode
"-dBATCH", # Batch mode
"-dNOPAUSE", # Don't pause between pages
"-sDEVICE=pngalpha", # Sets the output to an alpha channeled PNG
"-r300", # Sets resolution to 300 DPI
"-dTextAlphaBits=4", # Improves text output
"-dGraphicsAlphaBits=4", # Improves graphics output
"-sOutputFile=`"$finalOutputDirectory\Slide%03d.png`"", # Output file pattern
"`"$pdfPath`""
)
# Run Ghostscript to convert PDF to PNGs
$gsProcess = Start-Process -FilePath ($gsPath) -ArgumentList $arguments -NoNewWindow -PassThru
# Wait for Ghostscript to finish
$gsProcess.WaitForExit()
# Display a success message
Write-Host "PDF $pdfPath converted to PNG files in $finalOutputDirectory"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment