Bash – How to convert a color pdf to black-white

bashcolor-managementghostscriptimagemagickpdf

I'd like to transform a pdf with some coloured text and images in another pdf with only black&white, in order to reduce its dimensions. Moreover, I would like to keep the text as text, without transforming the pages elements in pictures.
I tried the following command:

convert -density 150 -threshold 50% input.pdf output.pdf

found in another question, a link, but it does what I don't want: the text in the output is transformed in a poor image and is no longer selectable.
I tried with Ghostscript:

gs      -sOutputFile=output.pdf \
        -q -dNOPAUSE -dBATCH -dSAFER \
        -sDEVICE=pdfwrite \
        -dCompatibilityLevel=1.3 \
        -dPDFSETTINGS=/screen \
        -dEmbedAllFonts=true \
        -dSubsetFonts=true \
        -sColorConversionStrategy=/Mono \
        -sColorConversionStrategyForImages=/Mono \
        -sProcessColorModel=/DeviceGray \
        $1

but it gives me the following error message:

./script.sh: 19: ./script.sh: output.pdf: not found

Is there any other way to create the file?

Best Answer

The gs example

The gs command you're running above has a trailing $1 which is typically meant for passing command line arguments into a script. So I'm not sure what you actually tried but I'm guessing that you tried to put that command into a script, script.sh:

#!/bin/bash

gs      -sOutputFile=output.pdf \
        -q -dNOPAUSE -dBATCH -dSAFER \
        -sDEVICE=pdfwrite \
        -dCompatibilityLevel=1.3 \
        -dPDFSETTINGS=/screen \
        -dEmbedAllFonts=true \
        -dSubsetFonts=true \
        -sColorConversionStrategy=/Mono \
        -sColorConversionStrategyForImages=/Mono \
        -sProcessColorModel=/DeviceGray \
        $1

And run it like this:

$ ./script.sh: 19: ./script.sh: output.pdf: not found

Not sure how you setup this script but it needs to executable.

$ chmod +x script.sh

Something definitely doesn't seem right with that script though. When I tried it I got this error instead:

Unrecoverable error: rangecheck in .putdeviceprops

An alternative

Instead of that script I'd use this one from the SU question instead.

#!/bin/bash

gs \
 -sOutputFile=output.pdf \
 -sDEVICE=pdfwrite \
 -sColorConversionStrategy=Gray \
 -dProcessColorModel=/DeviceGray \
 -dCompatibilityLevel=1.4 \
 -dNOPAUSE \
 -dBATCH \
 $1

Then run it like this:

$ ./script.bash LeaseContract.pdf 
GPL Ghostscript 8.71 (2010-02-10)
Copyright (C) 2010 Artifex Software, Inc.  All rights reserved.
This software comes with NO WARRANTY: see the file PUBLIC for details.
Processing pages 1 through 2.
Page 1
Page 2
Related Question