Setting auto height / width for converted Jpeg from PDF using GhostScript

I use GS to convert from PDF to JPEG and follow the command I use:

gs -sDEVICE=jpeg -dNOPAUSE -dBATCH -g500x300 -dPDFFitPage -sOutputFile=image.jpg image.pdf 

In this command, since you can see that -g500x300 is to set the size of the converted image (width x height).

Is there a way to simply set the width without having to enter the height so that it is based on the width to scale the height using its original aspect ratio? I know this can be achieved using ImageMagick convert, where you just put 0 on the height parameter ie -resize 500x0 . I tried with GhostScript, but I don't think this is the right way to do this.

I decided not to use ImageMagick conversion because it is very slow when it comes to converting large PDFs with multiple pages.

Thanks for the help!

+7
source share
2 answers

This post explains why ghostscript is faster - https://serverfault.com/questions/167573/fast-pdf-to-jpg-conversion-on-linux-wanted , and the only workaround to fix it would be to modify the imagemagick code.

Unfortunately, auto-sensing output is not supported by ghostscript. This is primarily due to the fact that the -g option used actually determines the size of the device that will contain the output, and not the processed output itself. This output size changes due to the -dPDFFitPage switch, which then tries to match the size of the device. And although you can only determine the height of jpeg 'device' with -dDEVICEHEIGHT=n , this will cause the width of the device to remain unchanged by default.

Despite a somewhat tedious workaround, you can use ghostscript or imagemagick to get the width and height of the PDF pages. To do this, using ghostscript, see Response to Using GhostScript to get page size . You can then calculate the correct width to set the -g flag to maintain aspect ratio. Bonus points if you can find one set of teams to do it all :)

+5
source

You can write a PostScript program to do this fairly easily. Here is the start:

  %!
 % usage: gs -sFile = ____. pdf scale.ps

 / File where not {
   (\ n *** Missing source file. \ (use -sFile = ____. pdf \) \ n) =
   Usage
 } {
   pop
 } ifelse

 % Get the width and height of a PDF page
 %
 / GetSize {
   pdfgetpage currentpagedevice
   1 index get_any_box 
   exch pop dup 2 get exch 3 get
   / PDFHeight exch def
   / PDFWidth exch def
 } def


 %
 % The main loop
 % For every page in the original PDF file
 %
 1 1 PDFPageCount 
 {
   / PDFPage exch def
   PDFPage GetSize

 % In here, knowing the desired destination size
 % calculate a scale factor for the PDF to fit
 % either the width or height, or whatever
 % The width and height are stored in PDFWidht and PDFHeight
   PDFPage pdfgetpage
   pdfshowpage
 } for

pdfgetpage and pdfshowpage are internal Posthost Ghostscript extensions for processing PDF files.

+4
source

All Articles