Search code examples
bashshellloopspdfgraphicsmagick

How to write a loop in shell for graphicsmagick?


I managed (with the help of SO) to make perfect png-snippets from a pdf file with graphicsmagick. My pdf contains text and formula each "snippet" on a single page. My command trims the content of a page to the very content and finally scales this up to 2000 pixel width.

Untill now, I need to repeat that command for each single page in every pdf. I am wondering how to automate this. I think I could try a loop for the repetition of the command for every page i untill the last page.

Assume file1.pdf is in my current working directory.

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
...

How can I set a counter and run a loop for every page in my document?


Solution

  • You are in luck. GraphicsMagick knows how to do that for you:

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

    If you are ok using ImageMagick instead, you can set the starting output file number to 1 instead of 0 and don't need the -adjoin:

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

    Or, if you want them all done in parallel, use GNU Parallel:

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