Convert a catalog of images into one PDF file

I have an image directory:

path/to/directory/
   image01.jpg
   image02.jpg
   ...

      

and would like to convert it to one PDF file:

path/to/directory.pdf

      

This is what I have managed to write so far:

#!/bin/bash

echo Directory $1
out=$(echo $1 | sed 's|/$|.pdf|')
echo Output $out

mkdir tmp

for i in $(ls $1)
do
    # MAC hates sed with "I" (ignore case) - thanks SO for the perl solution!
    # I want to match "jpg, JPG, Jpg, ..."
    echo $1$i $(echo "tmp/$i" | perl -C -e 'use utf8;' -pe 's/jpg$/pdf/i')
    convert $1$i $(echo "tmp/$i" | perl -C -e 'use utf8;' -pe 's/jpg$/pdf/i')
done

pdftk tmp/*.pdf cat output $out
rm -rf tmp

      

So the idea was to convert each image to a PDF file using imagemagick and use pdftk to merge it into one file. Thanks to the naming of the files, I don't have to worry about ordering.

Since I'm new to this, I'm sure there are many refinements that can be made:

  • only iterate over the image files in the directory (in case there is some Readme.txt, ...)
  • including extensions png, jpeg, ...
  • using trailing "/" is not elegant. I admit
  • and etc.

My main problem currently is that there are times when my directories and image files contain spaces in their names. The for-loop then iterates over the substrings of the filename, and I figure the line with the conversion will fail as well. I've tried some things but haven't succeeded so far and hope someone can help me here. If anyone has any ideas for solving the problems listed above, I would be very happy to hear them.

+3


source to share


1 answer


convert

can do it in one go:

convert *.[jJ][pP][gG] output.pdf

      

Or answer a few other questions and replace the script:



#!/bin/bash
shopt -s nullglob nocaseglob
convert "$1"/*.{png,jpg,jpeg} "${1%/}.pdf"

      

will iterate over all specified extensions in the first argument, regardless of its capitalization, and write in yourdir.pdf

. It won't split into spaces.

+7


source







All Articles