Search code examples
macospdftiffghostscript

Use Ghostscript to convert every file in a folder automatically


At the moment I'm using this command to convert file X.pdf to X.tif .

gs -q -sDEVICE=tiffg4 -r300 -dBATCH -dPDFFitPage -dNOPAUSE -sOutputFile=tif/X.tif pdf/X.pdf

Is there a smooth way to do the equivalent of

gs -q -sDEVICE=tiffg4 -r300 -dBATCH -dPDFFitPage -dNOPAUSE -sOutputFile=tif/*.tif pdf/*.pdf as one would do with say search queries? (I replaced the X with *) It obviously doesn't work with this method, but maybe there is a similiar syntax? Or am I going to have to write a batch file or something like that?

PS: Im on OSX


Solution

  • Try saving this as tif2pdf in the directory containing subdirectories tif and pdf:

    #!/bin/bash
    
    # Change into the "tif" directory to find the input files
    cd tif || { echo ERROR: Subdirectory tif not found; exit 1; }
    
    # Loop through all files ending in ".tif"
    for f in *.tif; do
    
       # Determine output filename
       out=${f%%tif}
       out="../pdf/${out}pdf"
    
       # Show the command we would run
       echo gs -q -sDEVICE=tiffg4 -r300 -dBATCH -dPDFFitPage -dNOPAUSE -sOutputFile="$out" "$f"
    done
    

    Then go in that directory in Terminal and make this script executable with:

    chmod +x tif2pdf
    

    Then run it with:

    ./tif2pdf
    

    At the moment, it does nothing, except show you what it would do. If you like the appearance of the commands it makes up, edit the script and remove the word echo in the penultimate line and run it again to actually do the conversions.

    Sample Output

    gs -q -sDEVICE=tiffg4 -r300 -dBATCH -dPDFFitPage -dNOPAUSE -sOutputFile=../pdf/a.pdf a.tif
    gs -q -sDEVICE=tiffg4 -r300 -dBATCH -dPDFFitPage -dNOPAUSE -sOutputFile=../pdf/b.pdf b.tif
    

    I suggest running it on a COPY of your files first.