Convert PDF to images using PowerShell and ImageMagick

Recently I had a lot of PDF files that I needed to convert to images. I needed it mostly for compression purposes. To get this done I started with experiments with GhostScript. However I didn’t get the results I wanted mostly because of my experience with it. So after a while I switched to ImageMagick and it ended up being pretty straight forward as well as delivering very nice compression results.

So after doing 1 file I created and programmed the script around to handle input from the pipeline by the FileInfo object so that you could use Get-ChildItem as input recursively if you wanted that.

The end result? I did Get-ChildItem C:\path -Filter “*.pdf” | Export-Image and awaaaay we go. The script defaults to a density of 300 and with the extention being PNG but you can change it if you like.

The script is not perfect or anything but it works.

This is a simple Powershell script that allows you to export images from a PDF file based on various preferences.

The script uses ImageMagick to export images from a PDF based on various command line switch options based on your preferences. 
It uses FileInfo input so Get-ChildItem or a direct file can work.

./Export-Image -File C:\example.pdf -Density 300 -Quality 100 -Extention "png"


    [Parameter(Mandatory=$true, ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true)][System.IO.FileInfo]$File,
    [ValidateSet('png', 'gif', 'jpg', 'jpeg')][string]$Extention = "png",
    [ValidateRange(1, 1200)][int]$Density = 300,
    [ValidateRange(1, 100)][int]$Quality = 100,

    if (-Not ($ImageMagick))
        $ImageMagick = "C:\Program Files\ImageMagick-7.0.9-Q16\magick.exe"

    if (-Not(Test-Path $ImageMagick))
        Write-Error "The ImageMagick installation path file you selected does not exist, please (re)install and try again"

    $Destination = $File.FullName -replace ($File.Extention), ("." + $Extention)

    if (-Not ($Overwrite))
        if (Test-Path $Destination)
            Write-Error "$Destination already exists, please use the Overwrite switch to force overwriting the destination file"
        Remove-Item $Destination -Force -ErrorAction SilentlyContinue

    $Arguments = '/c magick -density ' + $Density + ' -quality ' + $Quality + ' "' + $File.FullName + '" "' + $Destination + '"'
    Write-Verbose $Arguments

    Start-Process cmd -ArgumentList $Arguments -Wait -WindowStyle hidden

Leave a Comment