amitdar
amitdar

Reputation: 927

ImageMagick convert pdf to png with fixed width or height

I'm converting PDF file to PNG using ImageMagick's convert in that way:

convert -density 150 file.pdf -quality 100 res.png

The problem is that the size of the result pictures different according to the file content. How can I choose a specific max height and max width in pixels to the result picture ?

Upvotes: 2

Views: 8077

Answers (1)

Mark Setchell
Mark Setchell

Reputation: 207425

Updated Answer

From your comments, I think I understand better what you want now. So, I think the identity you need is this:

Required Resolution       Required Height
-------------------    =  ---------------
Current Resolution        Current Height

but remember that applies in both X- and Y-directions. So, let's let ImageMagick work out the x-resolution and the y-resolution you need to get your desired output size - it is easier to do it with ImageMagick's fx method because that works on both Windows and Linux and I happen to know you have ImageMagick installed already, whereas you may not have bc or anything on Windows to do maths:

#!/bin/bash
# New width and new height that you want
nh=1000
nw=500

# Calculate Resolution needed in Height
rh=$(identify -format "%[fx:int(($nh*resolution.y)/h)]" doc.pdf)
echo $rh

# Calculate Resolution needed in Width
rw=$(identify -format "%[fx:int(($nw*resolution.x)/w)]" doc.pdf)
echo $rw

So, if I use that on a file called doc.pdf that measures 595x842, it outputs 85 and 60 for the x and y density. And if I then use

convert -density 85 doc.pdf a.jpg

it comes out at 702x994 - which is close to the height of 1000 I wanted

and if I use

convert -density 60 doc.pdf a.jpg

it comes out at 496x702 which is close to the width of 500 I wanted.

In the foregoing, you can just use:

identify -format "%[fx:int(($nh*resolution.y)/h)]" doc.pdf

rather than assign the result to a variable like I did -I just do that because I generally want to use the variable later.

Original Answer

Just add a -resize WIDTHxHEIGHT in there after the conversion to set the size you want. So, in concrete terms, if you want it no more than 1500x2000 whilst retaining the original aspect ratio, do:

convert -density 150 file.pdf -quality 100 -resize 1500x2000 res.png

If you want it no more than 800px wide, and don't care about the height, do:

convert -density 150 file.pdf -quality 100 -resize 800x res.png

If you want it no more than 1000px tall, and don't care about the width, do:

convert -density 150 file.pdf -quality 100 -resize x1000 res.png

If you like the "Hall of Mirrors" effect, and want it 1200x1800 come what may, and to heck with the aspect ratio, do:

convert -density 150 file.pdf -quality 100 -resize 1200x1800! res.png

Upvotes: 5

Related Questions