如何在 shell 中为 graphicsmagick 编写循环?

How to write a loop in shell for graphicsmagick?

我设法(在 SO 的帮助下)使用 graphicsmagick 从 pdf 文件制作了完美的 png 片段。我的 pdf 在单个页面上包含每个 "snippet" 的文本和公式。我的命令将页面内容裁剪到最实际的内容,并最终将其缩放到 2000 像素宽度。

到目前为止,我需要为每个 pdf 中的每个页面重复该命令。我想知道如何使它自动化。我想我可以尝试循环为每一页重复命令,直到最后一页。

假设 file1.pdf 在我当前的工作目录中。

gm convert -density 300x300 file1.pdf[0] -trim -resize 2000x file1_page1.png
gm convert -density 300x300 file1.pdf[1] -trim -resize 2000x file1_page2.png
gm convert -density 300x300 file1.pdf[2] -trim -resize 2000x file1_page3.png
...

如何为文档中的每一页设置计数器和运行循环?

for file in *.pdf
do
    pages=$(identify "$file" | wc -l)
    for (( i=0; i<$pages; i++ ))
    do
        name=$(sed "s/\.pdf$/$i.png/g" <<< "$file");
        gm convert -density 300x300 "$file[$i]" -trim -resize 2000x "$name"
    done
done

试试这个。 它将每个 *.pdf 文件中的每个页面转换为 .png。

你很幸运。 GraphicsMagick 知道如何为您做到这一点:

gm convert -density 300x300 input.pdf -trim -resize 2000x +adjoin output-%d.png

如果您可以使用 ImageMagick,您可以将起始输出文件编号设置为 1 而不是 0,并且不需要-adjoin:

convert -density 300x300 input.pdf -scene 1 -trim -resize 2000x output-%d.png

或者,如果您希望它们全部并行完成,请使用 GNU Parallel:

parallel gm convert -density 300x300 {} -trim -resize 2000x output-{#}.png  ::: $(identify input.pdf | awk '{print }')