[Tex/LaTex] Choosing whether to include PDF or PNG in PDFLaTeX

graphicspdftexpng

Can I tell graphicx somehow which graphic format to choose when I omit the file extension in includegraphics and both a PDF and a PNG version of the same image exist? The reason is that I have some very large PDF vector graphics (in terms of file size/drawing primitives) that take a pretty long time to load each time I view the document. I would like to convert them to PNGs while working on the document and only use the PDF versions in the final document. Therefore, a global option that I can switch in the end would be great.

An additional plus would be to do the conversion to PNG on the fly during the LaTeX run if there is a PDF that has not been converted to PNG yet, if a tool for that exists. (I know how to use convert, but not how to include it automatically in LaTeX.)

Best Answer

The order of preference when files with the same name and different extensions is

.png .pdf .jpg .mps .jpeg .jbig2 .jb2 .PNG .PDF .JPG .JPEG .JBIG2 .JB2

which is stored in the macro \Gin@extensions. So if you have both image.png and image.pdf, pdflatex will load the former.

If you are mixing case in extensions, then

\DeclareGraphicsExtensions{%
    .png,.PNG,%
    .pdf,.PDF,%
    .jpg,.mps,.jpeg,.jbig2,.jb2,.JPG,.JPEG,.JBIG2,.JB2}

will ensure that PNG are always preferred over PDF files. For the final version it will be sufficient to switch the two lines.

A handier way, suggested by Heiko Oberdiek, is to use the package grfext:

\usepackage{grfext}
\PrependGraphicsExtensions*{.png,.PNG}

that will have the same effect without the need to check in pdftex.def for the list of extensions.

If you want also automatic conversion, you can say

\usepackage{graphicx}
\usepackage{epstopdf}
\epstopdfDeclareGraphicsRule{.pdf}{png}{.png}{convert #1 \OutputFile}
\DeclareGraphicsExtensions{%
    .png,.PNG,%
    .pdf,.PDF,%
    .jpg,.mps,.jpeg,.jbig2,.jb2,.JPG,.JPEG,.JBIG2,.JB2}

When image.pdf exists but not image.png, the file image-pdf-converted-to.png will be created and loaded in its place. Add the options you prefer between convert and #1 (for example -density 100 or something like that).

You need to call pdflatex with the --shell-escape option for this automatic conversion to work. Of course you'll comment out the \epstopdfDeclareGraphicsRule command for the final version, when only PDF files should be loaded (and switch the order of precedence in the lines below).