Warm tip: This article is reproduced from serverfault.com, please click

Convert image to pdf with Imagemagick keeping image resolution and placing it on top left corner

发布于 2020-12-15 09:55:32

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?

Questioner
Pietro Siccardi
Viewed
0
Pietro Siccardi 2020-12-15 21:17:57

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"