如何将图像批量转换为 PDF?

Gru*_*bel 11 pdf convert-command

我想将图像(jpg、png 等)批量转换为 PDF。将它们直接转换为 PDF 很容易:

convert in.jpg out.pdf
Run Code Online (Sandbox Code Playgroud)

但是我需要更多选项,例如设置输出页面大小、边距以及横向和纵向格式之间的旋转。经过一些试验和错误,我想出了:

convert -rotate "90>" -page A4+0+0  -gravity center in.jpg  out.pdf
Run Code Online (Sandbox Code Playgroud)

这使图像在 A4 页面上居中并自动在横向和纵向之间旋转,但它仅适用于 595x842 以下的小图像。较大的图像会中断,因为 595x842 似乎是分配给 A4 页面的像素分辨率。在网上阅读,-density选项可能是增加 A4 页面像素数的潜在解决方案,但我无法使其工作。

Imagemagick 之外的解决方案当然也受欢迎。

Gru*_*bel 8

一种解决方法是拆分图像生成和 PDF 转换。首先将图像via转换convert为A4@300dpi(即3508x2479),然后使用sam2p将它们转换为PDF,然后使用sam2p_pdf_scale将它们转换为A4。

convert -rotate "90>" -scale 3508x2479 -border 64x64 -bordercolor white in.png out.png
sam2p out.png out.pdf
sam2p_pdf_scale 595 842 out.pdf
Run Code Online (Sandbox Code Playgroud)

编辑:一个更完整的脚本:

#!/bin/sh

A4_WIDTH=2479
A4_HEIGHT=3508

H_MARGIN=64
V_MARGIN=64
WIDTH=$((${A4_WIDTH} - ${H_MARGIN} * 2))
HEIGHT=$((${A4_HEIGHT} - ${V_MARGIN} * 2))

for i in "$@"; do
    TMP="/tmp/$(uuidgen).png"
    echo "$i"
    convert \
        -rotate "90>" \
        -scale "${WIDTH}x${HEIGHT}" \
        -border "${H_MARGIN}x${V_MARGIN}" -bordercolor white \
        -gravity center \
        -extent "${A4_WIDTH}x${A4_HEIGHT}" \
        -gravity center \
        -font helvetica -pointsize 80 \
        -fill white -draw \
        "push graphic-context
         translate $((${A4_WIDTH}/2 - 160)), 0
         rotate 90
         text -2,-2 '$i'
         text -2,2 '$i'
         text 2,-2 '$i'
         text 2,2 '$i'
         pop graphic-context
    " \
        -fill black -draw \
        "push graphic-context
         translate $((${A4_WIDTH}/2 - 160)), 0
         rotate 90
         text 0,0 '$i'
         pop graphic-context
    " \
        "$i" "$TMP"
    sam2p "$TMP" "${i}.pdf"
    sam2p_pdf_scale 595 842 "${i}.pdf"
done

# EOF #
Run Code Online (Sandbox Code Playgroud)