.jpg를 .pdf(정의된 페이지 크기 및 테두리 포함)에 가운데 맞추는 방법은 무엇입니까?

.jpg를 .pdf(정의된 페이지 크기 및 테두리 포함)에 가운데 맞추는 방법은 무엇입니까?

.jpg를 .pdf로 변환하여 .jpg가 A4 페이지 중앙에 위치하도록 하고 이미지와 페이지 테두리 사이의 최소 테두리는 30픽셀이 되도록 하고 싶습니다.

내 출발점은 다음과 같습니다(JPG와 동일한 크기의 PDF를 생성합니다).

convert image.jpg image.pdf

답변1

나는 네 면 모두에 30px의 테두리를 추가하고 싶다고 가정합니다. -border크기 및 -bordercolor색상 옵션 사용 :

convert -border 30 -bordercolor white input.png output.pdf

자세한 내용은 여기에서 확인할 수 있습니다.Imagemagick - 이미지 가장자리 추가/제거

최종 PDF에 특정 크기를 지정하려면 다음 옵션을 사용할 수 있습니다.

convert \
  -page A4 \
  -gravity northwest \
  -border 30 \
  -bordercolor white \
  input.png output.pdf

답변2

다음은 원하는 작업을 수행하고 동시에 여러 .jpg 파일에 작업을 수행하여 각 파일을 자체 한 페이지 .pdf 파일로 변환할 수 있는 작은 스크립트입니다.

스크립트를 다른 이름으로 저장 imgs_to_pdfs.sh하고 다음과 같이 하나 이상의 파일 이름 인수를 사용하여 호출합니다.

./imgs_to_pdfs.sh myimg1.jpg myimg2.jpg img-*.jpg

출력 파일 이름은 입력 파일 이름과 일치하며 .jpg는 .pdf로 대체됩니다. 그래서스크립트가 실수로 기존 파일을 덮어쓰지 않도록 하세요!

어떻게 작동하나요?

  • 이미지를 로드하는 페이지의 경우 스크립트는 A4 형식을 사용합니다. ImageMagick의 최신 버전은 더 이상 A4 키워드를 지원하지 않는 것 같기 때문에 자체적으로 A4 크기를 계산합니다.
  • 이미지는아니요특정 해상도에서 A4 PDF 페이지 캔버스 중앙에만 표시되도록 스크립트로 리샘플링("크기 조정")되었습니다. 따라서 축소해도 이미지 정보가 손실되지 않으며, 확대해도 파일 크기가 불필요하게 늘어나지 않습니다.
  • 30픽셀의 최소 여백을 설정하는 대신 스크립트는 이미지와 PDF 페이지 테두리 사이에 공간을 남겨둡니다. 이미지에 흰색 테두리를 추가하는 것보다 이렇게 하면 파일 크기가 늘어나지 않으며 필요한 경우 나중에 유사한 명령을 사용하여 PDF에서 수정되지 않은 이미지를 추출할 수 있다는 장점이 있습니다.pdfimages -j file.pdf img.
  • 기본적으로 이미지 주변의 테두리는 각 페이지 크기의 ≥5%로 설정됩니다. 이를 달성하기 위해 이미지의 크기가 조정되므로 이미지 크기에 따라 x 차원 경계는 5%이고 y 차원 경계는 더 커지거나 그 반대가 됩니다. 스크립트에서 해상도 요소를 조정하여 테두리 크기를 조정할 수 있습니다. 현재 1.1A4 페이지의 해상도는 110%입니다. 따라서 이미지는 A4 페이지 크기의 90%만 차지하고 5% 테두리 두 개가 남습니다. 요소를 로 설정하면 1.2두 개의 10% 테두리가 생성됩니다.

그 외 세부 사항

  • 다음은 스크립트의 공식이 어떻게 5% 한계를 산출하는지에 대한 증거입니다.
    1. 페이지 크기(픽셀)는 다음과 같이 계산됩니다.page_size_x = density * 8.27
    2. 밀도는 다음과 같이 계산됩니다 density = img_size_x / 8.27 * 1.1. (이것은 x 차원에서 테두리의 5%를 비워두기 위해 더 높은 밀도가 필요하다고 가정합니다.)
    3. 1행의 2행은 다음을 생성합니다 page_size_x = (img_size_x/8.27*1.1) * 8.27 = img_size_x * 1.1. 실제로 페이지는 이미지 픽셀 너비의 110%이고 5% 테두리가 두 개 있습니다.
  • 수술이 필요한 사람도 있는 것 같습니다 -repage(여기처럼) 페이지 크기가 약간 "어긋나는" 것을 방지합니다. 필수는 아니지만 필요한 경우 시도해 보거나 통화의 마지막 작업으로 수행 -repage ${page_size_x}x${page_size_y}하세요 .-repage A4convert

스크립트 소스 코드

#!/bin/bash
# Converts input images to one-page PDF files each, without changing image data.
# The image is centered on a A4 page with a 5% border.

# bc function to calculate maximum of two floats
bc_functions="
define max(a,b) {
  if (a>b) {
    return(a)
  } else {
   return(b)
  }
} ";

for file in "$@"; do \
  # Determine image dimensions in pixels.
  img_size_x=$(identify -format "%w" "$file");
  img_size_y=$(identify -format "%h" "$file");

  # Calculate image density (in dpi) needed to fit the image and a 5% 
  # border all around on an A4 page (8.27x11.69"). Factor 1.1 creates 
  # 2*5% borders, see https://unix.stackexchange.com/a/220114 for details.
  min_density_x=$(echo "$img_size_x/8.27*1.1"  | bc -l);
  min_density_y=$(echo "$img_size_y/11.69*1.1" | bc -l);
  # Use the higher density to prevent any dimension exceeding the required fit.
  density=$(echo "$bc_functions max($min_density_x,$min_density_y)" | bc -l);

  # Calculate canvas dimensions in pixels.
  # (Canvas is an A4 page (8.27x11.69") with the calculated density.)
  page_size_x=$(echo  "8.27*$density" | bc -l);
  page_size_y=$(echo "11.69*$density" | bc -l);

  # Center image on a larger canvas (with a size given by "-extent").
  convert "$file" \
    -gravity center -extent ${page_size_x}x${page_size_y} \
    -units PixelsPerInch -density $density \
    -format pdf -compress jpeg \
    "${file/.jpg/.pdf}";
done;

인용하다

답변3

페이지 중앙에 이미지를 배치하기 위해 테두리를 사용하게 된 방식은 페이지를 지정하고 크기와 범위 기하학을 조정하는 것이었습니다. 크기를 조정할 크기와 두 차원 모두에서 테두리 크기의 2배로 축소된 범위입니다.

페이지 크기 치수는 다음에 나열되어 있습니다.http://www.imagemagick.org/script/command-line-options.php#page

문자(612x792)의 경우:

convert -page Letter -resize 552x732\> -extent 552x732 -background white -gravity Center -border 30 -bordercolor white image.jpg image.pdf

A4(595x842)의 경우:

convert -page A4 -resize 535x782\> -extent 535x782 -background white -gravity Center -border 30 -bordercolor white image.jpg image.pdf

답변4

정답은https://unix.stackexchange.com/a/220114-extent테두리에 공백을 추가하여 소스 이미지를 수정하려면 옵션을 사용하십시오 .

이 스크립트는 -page오프셋이 있는 옵션을 사용하여 캔버스 크기를 조정하고 이미지 위치를 조정하지만 이미지는 수정되지 않습니다. 바라보다Github의 스크립트여기에 복사하세요.

#!/bin/bash
# Converts input images to one-page PDF files each, without changing image data.
# The image is centered on a A4 page with a 5% border.
# Adapted from https://unix.stackexchange.com/a/220114
#
# Usage: [command] image1.jpg image2.png ...
# Output: PDF files named after the images e.g. image1.pdf


# bc function to calculate maximum of two floats
bc_functions="
define max(a,b) {
  if (a>b) {
    return(a)
  } else {
    return(b)
  }
};";

# Do the calculation in string $1 and echo the result.
function calc {
  # Define bc functions so we can use it for the calc.
  echo "$bc_functions $1" | bc -l;
}


for file in "$@"; do \
  # Determine image dimensions in pixels.
  img_size_x=$(identify -format "%w" "$file");
  img_size_y=$(identify -format "%h" "$file");

  # Calculate image density (in dpi) needed to fit the image and a 5% 
  # border all around on an A4 page (8.27x11.69"). Factor 1.1 creates 
  # 2*5% borders, see https://unix.stackexchange.com/a/220114 for details.
  min_density_x=$(calc "$img_size_x / 8.27 * 1.1");
  min_density_y=$(calc "$img_size_y / 11.69 * 1.1");

  # Use the higher density to prevent any dimension exceeding the required fit.
  density=$(calc "max($min_density_x,$min_density_y)");

  # Calculate canvas dimensions in pixels.
  # (Canvas is an A4 page (8.27x11.69") with the calculated density.)
  page_size_x=$(calc "8.27 * $density");
  page_size_y=$(calc "11.69 * $density");

  offset_x=$(calc "($page_size_x - $img_size_x) / 2 * 72 / $density");
  offset_y=$(calc "($page_size_y - $img_size_y) / 2 * 72 / $density");

  # Center image on a larger canvas.
  convert "$file" \
    -page ${page_size_x}x${page_size_y}+${offset_x}+${offset_y} \
    -units PixelsPerInch -density $density \
    -format pdf -compress jpeg \
    "${file/.jpg/.pdf}";
done;

이것은스크립트 작동 방식을 설명하는 더 자세한 기사, 그리고 그 사용법.

관련 정보