I'm trying to write a small program for Linux to resize PDFs and adjust margins. My plan was to use Ghostscript as a back-end. This Terminal command successfully resizes most PDFs:
gs -q -sDEVICE=pdfwrite -dBATCH -dNOPAUSE -dFIXEDMEDIA -dPDFFitPage \
-dDEVICEWIDTHPOINTS=300 -dDEVICEHEIGHTPOINTS=400 -sOutputFile=out.pdf file.pdf
The -dPDFFitPage
option scales pages to fit the new size, adding whitespace as padding if the image aspect ratio doesn't match the specified dimensions. Removing -dPDFFitPage
changes the page size without scaling - pages will be cropped if too large, or whitespace added if too small.
However, the command doesn't work with PDFs created by ImageMagick's "convert" program. The PDF is scaled but no whitespace is added so only one dimension will be correct in the output file. Without the -dPDFFitPage
option oversize images are cropped as expected, but nothing appears to happen if the image is smaller than the new page size (i.e. no whitespace is added).
It appears that the problem lies with the fact that the PDF is empty apart from the image. How can I get Ghostscript to adjust the page size and fill the empty part of the page with white if necessary?
Edit: Example files
To see the problem, try with these example files (there are also example Ghostscript output PDFs).
Alternatively, use ImageMagick (or any image editor) to create a suitable example image yourself:
convert -size 500x500 xc:skyblue -fill black -draw "circle 250,250 0,250" image.png
Now, use ImageMagick (NOT any other program) to convert it to a PDF:
convert image.png file.pdf
Now try this with the Ghostscript code. See what happens when you try it:
- with and without
-dPDFFitPage
- with the width and height smaller than the original, and with them larger
To see how it is supposed to work, try using any other tool to convert the example image to a PDF. You could (for example) use LibreOffice or LaTeX, or take the PDF you just made (the one that didn't work) and "Print" it to create another PDF (which for some reason will work). Make sure the image fills the entire page of the PDF (there should be no whitespace/border in the PDF you use to test with Ghostscript, but the output PDF created by Ghostscript should have some whitespace.)