I'm using imagemagick to convert images to pdf with A4 page format trying to keep image resolution and placing it on center of PDF (the images vary in extension and size). I tried this:
convert image.jpg -resize 595x842^\> -gravity center -background white -units PixelsPerInch -page a4 image.pdf
This command keeps the quality and the resolution of the image, but the image in the pdf appears on different positions depending on image size (An image with size 10109x4542 appears on bottom, another one with size 800x464 appears near the top of the page). Is there a way to keep resolution and place the image on center of PDF?
I found a solution of this problem. Here the bash code:
#!/bin/bash
if [ -z "$1" ] || [ -z "$2" ]
then
echo "Usage: $0 <input> <output>"
exit 1;
fi
max () {
echo $(( $1 > $2 ? $1 : $2 ))
}
IMAGE_X=$(identify -format "%w" "$1");
IMAGE_Y=$(identify -format "%h" "$1");
IMAGE_DENSITY_X=$(( $IMAGE_X * 100 / 827 ))
IMAGE_DENSITY_Y=$(( $IMAGE_Y * 100 / 1169 ))
IMAGE_DENSITY=$(max $IMAGE_DENSITY_X $IMAGE_DENSITY_Y)
echo "Image density: $IMAGE_DENSITY"
PAGE_SIZE_X=$(( $IMAGE_DENSITY * 827 / 100 ))
PAGE_SIZE_Y=$(( $IMAGE_DENSITY * 1169 / 100 ))
echo "Page size X: $PAGE_SIZE_X"
echo "Page size Y: $PAGE_SIZE_Y"
OFFSET_X=$(( ($PAGE_SIZE_X - $IMAGE_X) / 2 * 72 / $IMAGE_DENSITY ))
OFFSET_Y=$(( ($PAGE_SIZE_Y - $IMAGE_Y) / 2 * 72 / $IMAGE_DENSITY ))
echo "$IMAGE_DENSITY $PAGE_SIZE_X $OFFSET_X $OFFSET_Y"
convert "$1" \
-page ${PAGE_SIZE_X}x${PAGE_SIZE_Y}+${OFFSET_X}+${OFFSET_Y} \
-units PixelsPerInch \
-density $IMAGE_DENSITY \
-format pdf \
"$2"