I'm attempting to use GraphicsMagick in Ubuntu to convert hundreds of directories that contain multiple TIF files into one multi-page PDF file per directory. The folder depth is consistent with this structure:

Root/Limb_1/Branch_1/Twig_1/A.tif B.tif C.tif

So there would be one multi-page PDF per "Twig" directory.

To retain contextual information found in the file path, each multi-page PDF per directory would ideally be named with its given file path.

So output PDF files would be named like: Root_Limb_1_Branch_1_Twig_1.pdf

To the extent of producing 1 PDF per 1 TIF this question has been useful:

How to recursively and automatically convert all bmps to pngs in a given directory?

Especially the script provided by @andrew.46, which I've modified for my use case:

find . -name '*.tif' -type f -exec bash -c 'gm convert -monitor "$0" "${0%.tif}.pdf"' {} \;

Unfortunately, I don't know how to modify this script to output 1 PDF per directory; or how to produce the file path name per PDF.

Thanks for any and all input.

1 Answer 1


Assuming you've got your conversion running per directory, you just need to merge the PDFs with pdftk.

pdftk *.pdf cat output ${NAME:1}.pdf

The first line takes your full path and swaps slashes with underscores. The ${NAME:1} then skips the first character.

Here's a one-line monster, make sure you don't have anything called ".tif.pdf", or anything matching your desired output name, as they will get obliterated/modified.

find . -name '*.tif' -type f -exec bash -c 'gm convert -monitor "$0" "$0.pdf"; DD=$(dirname "$0"); DN=`eval "cd "$DD";pwd;cd - > /dev/null"`;  D="${DN//\//_}"; FN="${D:1}.pdf"; if [ -f "$FN" ]; then pdftk "$0.pdf" "$FN" cat output "$FN.tmp"; rm "$0.pdf"; else mv "$0.pdf" "$FN.tmp"; fi; mv "$FN.tmp" "$FN"' {} \;
  • Yes, this script is a monster, but it works! Could you please show me how to make the aggregated PDFs present each page in the original order of the source files? (e.g. 001187.tif = page1; 001188.tif = page2; 001189.tif = page3)
    – Darkivist
    Aug 9, 2019 at 15:47
  • try changing this part pdftk "$0.pdf" "$FN" cat output "$FN.tmp" to pdftk "$FN" "$0.pdf" cat output "$FN.tmp" maybe? (Swapping the order of the arguments for pdftk should probably change the order they are output). I'm not sure what order the script in the answer actually uses, ordering wasn't mentioned in the question so I paid no attention ;)
    – abb
    Aug 11, 2019 at 22:49
  • With this modification, your script reproduces the original order of the source files used in each aggregated PDF. Thanks!
    – Darkivist
    Aug 12, 2019 at 14:55

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.