[Tex/LaTex] Switching color and grayscale mode for \includegraphics

colorgraphicspdfpdftex

Suppose I have a document that includes a lot of colorful PDFs. Now I'd like to easily switch between "color" version and "greyscale version". I'm aware of \DeclareGraphicsRule, but I think this needs more tweaking. See the MWE below.

% engine: pdflatex
\documentclass{article}

\usepackage{xcolor,graphicx}

\iftrue
% code for "color" version
\else
% code for "grayscale" version
\fi

\begin{document}

\includegraphics{z4z.pdf}

\end{document}

You can use any image you want, but the one I used is here: http://kmlinux.fjfi.cvut.cz/~hejdato1/z4z.pdf

The command that can be used to convert image to greyscale is e.g.

convert -density 600 #1.pdf -colorspace Gray #2.pdf

Last but not least, it would be nice if it worked both with and wihout the .pdf extension in \includegraphics.

Best Answer

You have a classical vector drawing (z4z.pdf). With the command line with convert (ImageMagick) the image is converted to a bitmap. PDF can also contain bitmaps. A better way is using Inkscape. It has an option to convert to the colors to the gray color model. Save again as PDF, see below.

I would use two different directories, the first directory contains the color images, the second directory the grayscale images. Then it is easy to switch between them using \graphicspath. The current directory should be free of these images, otherwise they would be found first.

\documentclass{article}
\usepackage{xcolor,graphicx}

\iftrue % color
  \graphicspath{{img-color/}}
\else % grayscale
  \selectcolormodel{gray}
  \graphicspath{{img-gray/}}
\fi

\begin{document}
  \includegraphics[scale=.5]{z4z}
\end{document}

In case of grayscale the example also switches to the gray color model for the colors controlled by package xcolor. Also black/white is possible with option monochrome, but the option is needed at loading time of the color packages:

\documentclass{article}

\usepackage{graphicx}

%\iftrue % color
\iffalse
  \graphicspath{{img-color/}}
\else % grayscale
  \PassOptionsToPackage{monochrome}{xcolor}
  \graphicspath{{img-gray/}}
\fi

\usepackage{xcolor}

\begin{document}
  \includegraphics[scale=.5]{z4z}
\textcolor{yellow}{yellow}
\textcolor{red}{red}
\textcolor{blue}{blue}
\end{document}