Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save bbotelho3/6967e074130b86d5df2c to your computer and use it in GitHub Desktop.
Save bbotelho3/6967e074130b86d5df2c to your computer and use it in GitHub Desktop.
Convert a PDF file to black and white (not grayscale)
# The first approach that I found was to convert using a virtual device using Ghostscript.
# The virtual device, pdfwrite, supports parameters to convert the original PDF file to another PDF file in grayscale.
# In my case, I wanted only black and white, so this was not enough.
#!/bin/bash
gs \
-sOutputFile=output.pdf \
-sDEVICE=pdfwrite \
-sColorConversionStrategy=Gray \
-dProcessColorModel=/DeviceGray \
-dCompatibilityLevel=1.4 \
-dNOPAUSE \
-dBATCH \
$1
# I didn't find any solution that worked for my case, so I had to create my own.
# A question at StackOverflow asked the same question, the response was:
gs -o <output-file.pdf> -sDEVICE=pdfwrite \
-c "/osetcolor {/setcolor} bind def /setcolor {pop [0 0 0] osetcolor} def" \
-f <input-file.ps>
# What this does is redefine the setcolor function from PostScript to always set the color to black (0, 0, 0).
# This should work, but there are other functions that also set colors in PostScript.
# After some evaluation, I found that my PostScript file used setrgbcolor.
# The adapted solution is this:
gs -o output.pdf -sDEVICE=pdfwrite \
-c "/setrgbcolor {pop pop pop 0 setgray} bind def" \
-f $1
# I redefined setrgbcolor to pop all the previous parameters and to use the setgray function to set the color as black (0).
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment