# LaTeX/Importing Graphics

LaTeX

Getting Started

Common Elements

Mechanics

Technical Texts

Special Pages

Special Documents

Creating Graphics

Programming

Miscellaneous

Help and Recommendations

Appendices

edit this boxedit the TOC

There are two possibilities to include graphics in your document. Either create them with some special code, a topic which will be discussed in the Creating Graphics part, (see Introducing Procedural Graphics) or import productions from third party tools, which is what we will be discussing here.

Strictly speaking, LaTeX cannot manage pictures directly: in order to introduce graphics within documents, LaTeX just creates a box with the same size as the image you want to include and embeds the picture, without any other processing. This means you will have to take care that the images you want to include are in the right format to be included. This is not such a hard task because LaTeX supports the most common picture formats around.

## Raster graphics vs. vector graphics

Raster graphics will highly contrast with the quality of the document if they are not in a high resolution, which is the case with most graphics. The result may be even worse once printed.

Most drawing tools (e.g. for diagrams) can export in vector format. So you should always prefer PDF or EPS to PNG or JPG.

## The graphicx package

As stated before, LaTeX can't manage pictures directly, so we will need some extra help: we have to load the graphicx package[1] in the preamble of our document:

 \usepackage{graphicx}

This package accepts as an argument the external driver to be used to manage pictures; however, the latest version of this package takes care of everything by itself, changing the driver according to the compiler you are using, so you don't have to worry about this. Still, just in case you want to understand better how it works, here are the possible options you can pass to the package:

• dvips (default if compiling with latex), if you are compiling with latex to get a DVI and you want to see your document with a DVI or PS viewer.
• dvipdfm, if you are compiling with latex to get a DVI that you want to convert to PDF using dvipdfm, to see your document with any PDF viewer.
• pdftex (default if compiling with pdflatex), if you are compiling with pdftex to get a PDF that you will see with any PDF viewer.

But, again, you don't need to pass any option to the package because the default settings are fine in most of the cases.

In many respects, importing your images into your document using LaTeX is fairly simple... once you have your images in the right format that is! Therefore, I fear for many people the biggest effort will be the process of converting their graphics files. Now we will see which formats we can include and then we will see how to do it.

## Document Options

The graphics and graphicx packages recognize the draft and final options given in the \documentclass[...]{...} command at the start of the file. (See Document Classes.) Using draft as the option will suppress the inclusion of the image in the output file and will replace the contents with the name of the image file that would have been seen. Using final will result in the image being placed in the output file. The default is final.

## Supported image formats

As explained before, the image formats you can use depend on the driver that graphicx is using but, since the driver is automatically chosen according to the compiler, then the allowed image formats will depend on the compiler you are using.

Consider the following situation: you have added some pictures to your document in JPG and you have successfully compiled it in PDF. Now you want to compile it in DVI, you run latex and you get a lot of errors... because you forgot to provide the EPS versions of the pictures you want to insert.

At the beginning of this book, we had stated that the same LaTeX source can be compiled in both DVI and PDF without any change. This is true, as long as you don't use particular packages, and graphicx is one of those. In any case, you can still use both compilers with documents with pictures as well, as long as you always remember to provide the pictures in two formats (EPS and one of JPG, PNG or PDF).

### Compiling with latex

The only format you can include while compiling with latex is Encapsulated PostScript (EPS).

The EPS format was defined by Adobe Systems for making it easy for applications to import postscript-based graphics into documents. Because an EPS file declares the size of the image, it makes it easy for systems like LaTeX to arrange the text and the graphics in the best way. EPS is a vector format—this means that it can have very high quality if it is created properly, with programs that are able to manage vector graphics. It is also possible to store bit-map pictures within EPS, but they will need a lot of disk space.

### Compiling with pdflatex

If you are compiling with pdflatex to produce a PDF, you have a wider choice. You can insert:

• JPG, widely used on Internet, digital cameras, etc. They are the best choice if you want to insert photos.
• PNG, a very common format (even if not as much as JPG); it's a lossless format and it's the best choice for diagrams (if you were not able to generate a vector version) and screenshots.
• PDF, it is widely used for documents but can be used to store images as well. It supports both vector and bit-map images, but it's not recommended for the latter, as JPG or PNG will provide the same result using less disk space.
• EPS can be used with the help of the epstopdf package. Depending on your installation,
• you may just need to have it installed, there is no need to load it in your document;
• if it does not work, you need to load it just after the graphicx package. Additionally, since epstopdf will need to convert the EPS file into a PDF file and store it, you need to give "writing permissions" to your compiler. This is done by adding an option to the compiling command, e.g. pdflatex -shell-escape file.tex (if you use a LaTeX editor, they usually allow to modify the command in the configuration options). Check the epstopdf documentation for other compilers.

## Including graphics

Now that we have seen which formats we can include and how we could manage those formats, it's time to learn how to include them in our document. After you have loaded the graphicx package in your preamble, you can include images with \includegraphics, whose syntax is the following:

 \includegraphics[attr1=val1, attr2=val2, ..., attrn=valn]{imagename}

As usual, arguments in square brackets are optional, whereas arguments in curly braces are compulsory.

The argument in the curly braces is the name of the image. Write it without the extension. This way the LaTeX compiler will look for any supported image format in that directory and will take the best one (EPS if the output is DVI; JPEG, PNG or PDF if the output is PDF). Images can be saved in multiple formats for different purposes. For example, a directory can have "diagram.pdf" for high-resolution printing, while "diagram.png" can be used for previewing on the monitor. You can specify which image file is to be used by pdflatex through the preamble command:

 \DeclareGraphicsExtensions{.pdf,.png,.jpg}

which specifies the files to include in the document (in order of preference), if files with the same basename exist, but with different extensions.

The variety of possible attributes that can be set is fairly large, so only the most common are covered below:

 width=xx Specify the preferred width of the imported image to xx. NB. Only specifying either width or height will scale the image whilst maintaining the aspect ratio. height=xx Specify the preferred height of the imported image to xx. keepaspectratio This can be set to either true or false. When true, it will scale the image according to both height and width, but will not distort the image, so that neither width nor height are exceeded. scale=xx Scales the image by the desired scale factor. e.g, 0.5 to reduce by half, or 2 to double. angle=xx This option can rotate the image by xx degrees (counter-clockwise) trim=l b r t This option will crop the imported image by l from the left, b from the bottom, r from the right, and t from the top. Where l, b, r and t are lengths. clip For the trim option to work, you must set clip=true. page=x If the image file is a pdf file with multiple pages, this parameter allows you to use a different page than the first. resolution=x Specify image resolution in dpi

In order to use more than one option at a time, simply separate each with a comma. The order you give the options matters. E.g you should first rotate your graphic (with angle) and then specify its width.

Included graphics will be inserted just there, where you placed the code, and the compiler will handle them as "big boxes". As we will see in the floats section, this can disrupt the layout; you'll probably want to place graphics inside floating objects.

Also note that the trim option does not work with XeLaTex.

Be careful using any options, if you are working with the chemnum-package. The labels defined by \cmpdref{<label name>} might not behave as expected. Scaling the image for instance may be done by \scalebox instead.

The star version of the command will work for .eps files only. For a more portable solution, the standard way should take precedence. The star command will take the crop dimension as extra parameter:

 \includegraphics*[100,100][300,300]{mypicture}

### Examples

OK, it's time to see graphicx in action. Here are some examples. Say you had a file 'chick.jpg' you would include it like:

 \includegraphics{chick}

This simply imports the image, without any other processing. However, it is very large (so we won't give a example of how it would look here!) So, let's scale it down:

 \includegraphics[scale=0.5]{chick}

This has now scaled it by half. If you wish to be more specific and give actual lengths of the image dimensions, this is how to go about it:

 \includegraphics[width=2.5cm]{chick}

One can also specify the scale with respect to the width of a line in the local environment (\linewidth), the width of the text on a page (\textwidth) or the height of the text on a page (\textheight) (pictures not shown):

 \includegraphics[width=\linewidth]{chick} \includegraphics[width=\textwidth]{chick} \includegraphics[height=\textheight]{chick}

To rotate (I also scaled the image down):

 \includegraphics[scale=0.5, angle=180]{chick}

And finally, an example of how to crop an image should you wish to focus on one particular area of interest:

 %trim option's parameter order: left bottom right top \includegraphics[trim = 10mm 80mm 20mm 5mm, clip, width=3cm]{chick}

Note the presence of clip, as the trim operation will not work without it.

Trick: You can also use negative trim values to add blank space to your graphics, in cases where you need some manual alignment.

### Spaces in names

If the image file were called "chick picture.png", then you need to include the full filename when importing the image:

 \includegraphics[scale=0.5]{chick picture.png} chick picture.png

One option is to not use spaces in file names (if possible), or to simply replace spaces with underscores ("chick picture.png" to "chick_picture.png")

 \includegraphics[scale=0.5]{chick_picture.png}

### Borders

It is possible to have LaTeX create a border around your image by using \fbox:

 \setlength\fboxsep{0pt} \setlength\fboxrule{0.5pt} \fbox{\includegraphics{chick}}

You can control the border padding with the \setlength\fboxsep{0pt} command, in this case I set it to 0pt to avoid any padding, so the border will be placed tightly around the image. You can control the thickness of the border by adjusting the \setlength\fboxrule{0.5pt} command.

See Boxes for more details on \framebox and \fbox.

## Graphics storage

The command \graphicspath tells LaTeX where to look for images, which can be useful if you store images centrally for use in many different documents. The \graphicspath command takes one argument, which specifies the additional paths you want to be searched when the \includegraphics command is used. Here are some examples (trailing / is required):

 \graphicspath{ {/var/lib/images/} } \graphicspath{ {images_folder/}{other_folder/}{third_folder/} } \graphicspath{ {./images/} } \graphicspath{ {c:\mypict~1\camera} } \graphicspath{ {c:/mypict~1/camera/} } % works well in Win XP

Please see http://www.ctan.org/tex-archive/macros/latex/required/graphics/grfguide.pdf. In the third example shown there should be a directory named "images" in the same directory as your main tex file, i.e. this is RELATIVE addressing.

Using absolute paths, \graphicspath makes your file less portable, while using relative paths (like the third example), there should not be any problem with portability. The fourth example uses the "safe" (MS-DOS) form of the Windows MyPictures folder because it's a bad idea to use directory names containing spaces. Again, ensure file names do not contain spaces or alternatively if you are using PDFLaTeX, you can use the package grffile which will allow you to use spaces in file names.

Note that you cannot make the graphicx package search directories recursively. Under Linux/Unix, you can achieve a recursive search using the environment variable TEXINPUTS, e.g., by setting it to

export TEXINPUTS=./images//:./Snapshots//


before running latex/pdflatex or your TeX-IDE. (But this, of course, is not a portable method.)

## Images as figures

The figure environment is not exclusively used for images. We will only give a short preview of figures here. More information on the figure environment and how to use it can be found in Floats, Figures and Captions.

There are many scenarios where you might want to accompany an image with a caption and possibly a cross-reference. This is done using the figure environment. The following code sample shows the bare minimum required to use an image as a figure.

 \begin{figure}[p]     \includegraphics{image.png} \end{figure}

The above code extract is relatively trivial, and doesn't offer much functionality. The following code sample shows an extended use of the figure environment which is almost universally useful, offering a caption and label, centering the image and scaling it to 80% of the width of the text.

 \begin{figure}[p]     \centering     \includegraphics[width=0.8\textwidth]{image.png}     \caption{Awesome Image}     \label{fig:awesome_image} \end{figure}

## Seamless text integration

The drawback of importing graphics that were generated with a third-party tool is that font and size will not match with the rest of the document. There are still some workarounds though.

The easiest solution is to use the picture environment and then simply use the "put" command to put a graphics file inside the picture, along with any other desired LaTeX element. For example:

 \setlength{\unitlength}{0.8cm} \begin{picture}(6,5) \put(3.5,0.4){$\displaystyle s:=\frac{a+b+c}{2}$} \put(1,1){\includegraphics[   width=2cm,height=2cm]{picture.eps} } \end{picture}

Note that the border around the picture in the above example was added by using \fbox, so the contents of the border is the picture as generated by the above code.

Tools like Inkscape or Xfig have a dedicated LaTeX export feature that will let you use correct font and size for text in vector graphics. See #Third-party graphics tools.

For a perfect integration of graphics, you might consider procedural graphics capabilities of some LaTeX packages like TikZ or PSTricks. It lets you draw from within a document source. While the learning curve is steeper, it is worth it most of the time.

## Including full PDF pages

There is a great package for including full pages of PDF files: pdfpages. It is capable of inserting entire pages as is and more pages per one page in any layout (e.g. 2x3).

The package has several options:

 \usepackage[ options ]{pdfpages}

Options:

• final: Inserts pages. This is the default.
• draft: Does not insert pages, but prints a box and the filename instead.
• enable-survey: Activates survey functionalities. (Experimental, subject to change.)

The first command is

 \includepdf[ key=val ]{ filename }

Options for key=val (A comma separated list of options using the key = value syntax)

 pages Selects pages to insert. The argument is a comma separated list, containing page numbers (pages={3,5,6,8}), ranges of page numbers (pages={4-9}) or any combination. To insert empty pages use {}. For instance pages={3,{},8-11,15} will insert page 3, an empty page, and pages 8, 9, 10, 11, and 15. Actually not only links but all kinds of PDF annotations will get lost. Page ranges are specified by the following syntax: m - n. This selects all pages from m to n. Omitting m defaults to the first page; omitting n defaults to the last page of the document. Another way to select the last page of the document, is to use the keyword last. (This is only permitted in a page range.) E.g.: pages=- will insert all pages of the document, and pages=last-1 will insert all pages in reverse order. (Default: pages=1) angle You can use the angle-option for turning the included page, for exampe for turning a landscape document when the latex-document is portrait. Example: angle=90 addtolist Adds an entry to the list of figures, the list of tables, or any other list (e.g. from float.sty). This option requires four arguments, separated by commas: addtolist={ page number , type , heading , label } page number : Page number of the inserted page. type: Name of a floating environment. (figure, table, etc.) heading: Title inserted into LoF, LoT, etc. label: Name of the label. This label can be referred to with \ref and \pageref. Like addtotoc, addtolist accepts multiple sets of the above mentioned four arguments, all separated by commas. The proper recursive definition is: addtolist={ page number , type , heading , label [, lof-list ] } pagecommand Declares LaTeX-commands, which are executed on each sheet of paper. (Default: pagecommand={\thispagestyle{empty}} pagecommand={\label{fig:mylabel}}

You can also inserts pages of several external PDF documents.

 \includepdfmerge[ key=val ]{ file-page-list }

Several PDFs can be placed table-like on one page. See more information in its documentation.

## Converting graphics

Note

You should also take a look at Export To Other Formats for other possibilities.

epstopdf

You can convert EPS to PDF with the epstopdf utility, included in package of the same name. This tool is actually called by pdflatex to convert EPS files to PDF in the background when the graphicx package is loaded. This process is completely invisible to the user.

You can batch convert files using the command-line. In Bourne Shell (Unix) this can be done by:

$for i in *.eps; do epstopdf "$i"; done


In Windows, multiple files can be converted by placing the following line in a batch file (a text file with a .bat extension) in the same directory as the images:

for %%f in (*.eps) do epstopdf %%f


which can then be run from the command line.

If epstopdf produces whole page with your small graphics somewhere on it, use

$epstopdf --gsopt=-dEPSCrop foo.eps  or try using ps2pdf utility which should be installed with Ghostscript (required for any TeX distribution). $ ps2pdf -dEPSCrop foo.eps


to crop final PDF.

eps2eps

When all of the above fails, one can simplify the EPS file before attempting other conversions, by using the eps2eps tool (also see next section):

$eps2eps input.eps input-e2.eps  This will convert all the fonts to pre-drawn images, which is sometimes desirable when submitting manuscripts for publication. However, on the downside, the fonts are NOT converted to lines, but instead to bitmaps, which reduces the quality of the fonts. imgtops imgtops is a lightweight graphics utility for conversions between raster graphics (JPG, PNG, ...) and EPS/PS files. Inkscape Inkscape can also convert files from and to several formats, either from the GUI or from the command-line. For instance, to obtain a PDF from a SVG image you can do: $ inkscape -z -D --file=input.svg --export-pdf=output.pdf


It is possible to run this from within a LaTeX file, the Template:LaTeX/package package (when running (pdf)latex with the --shell-escape option) can do this using Inkscape's pdf+tex export option, or a simple macro can be used. See How to include SVG diagrams in LaTeX? -- Stackexchange See Export To Other Formats for more details.

pstoedit

To properly edit an EPS file, you can convert it to an editable format using pstoedit. For instance, to get an Xfig-editable file, do:

$pstoedit -f fig input.eps output.fig  And to get an SVG file (editable with any vector graphics tool like Inkscape) you can do: $ pstoedit -f plot-svg input.eps output.svg


Sometimes pstoedit fails to create the target format (for example when the EPS file contains clipping information).

PDFCreator

Under Windows, PDFCreator is an open source software that can create PDF as well as EPS files. It installs a virtual printer that can be accessed from other software having a "print..." entry in their menu (virtually any program).

Raster graphics converters

These three programs operate much the same way, and can convert between most graphics formats. Sam2p however is the most recent of the three and seems to offer both the best quality and to result in the smallest files.

### PNG alpha channel

Acrobat Reader sometimes has problems with displaying colors correctly if you include graphics in PNG format with alpha channel. You can solve this problem by dropping the alpha channel. On Linux it can be achieved with convert from the ImageMagick program:

convert -alpha off input.png output.png


### Converting a color EPS to grayscale

Sometimes color EPS figures need to be converted to black-and-white or grayscale to meet publication requirements. This can be achieved with the eps2eps of the Ghostscript package and [2] programs:

$eps2eps input.eps input-e2.eps$ pscol -0gray input-e2.eps input-gray.eps


## Third-party graphics tools

We will not tackle the topic of procedural graphics created from within LaTeX code here (TikZ, PSTricks, MetaPost and friends). See Introducing Procedural Graphics for that.

You should prefer vector graphics over raster graphics for their quality. Raster graphics should only be used in case of photos. Diagrams of any sort should be vectors.

As we have seen before, LaTeX handles

• EPS and PDF for vector graphics;
• PNG and JPG for raster graphics.

If some tools cannot save in those formats, you may want to convert them before importing them.

### Vector graphics

Dia

Dia is a cross platform diagramming utility which can export eps images, or generate tex drawn using the tikz package.

Inkscape

Another program for creating vector graphics is Inkscape. It can run natively under Windows, Linux or Mac OS X (with X11). It works with Scalable Vector Graphics (SVG) files, although it can export to many formats that can be included in LaTeX files, such as EPS and PDF. From version 0.48, there is a combined PDF/EPS/PS+LaTeX output option, similar to that offered by Xfig. There are instructions on how to save your vector images in a PDF format understood by LaTeX and have LaTeX manage the text styles and sizes in the image automatically.[1]. Today there is the svg-package[2] which provides an \includesvg command to convert and include svg-graphics directly in your LaTeX document using Inkscape. You may have a look at this extended example too.

An extremely useful plug-in is textext, which can import LaTeX objects. This can be used for inserting mathematical notation or LaTeX fonts into graphics (which may then be imported into LaTeX documents).

Ipe

The Ipe extensible drawing editor is a free vector graphics editor for creating figures in PDF or EPS format. Unlike Xfig, Ipe represents LaTeX fonts in their correct size on the screen which makes it easier to place text labels at the right spot. Ipe also has various snapping modes (for example, snapping to points, lines, or intersections) that can be used for geometric constructions.

lpic

Yet another solution is provided by the lpic packages [3], which allows TeX annotations to imported graphics. See Labels in the figures.

OpenOffice.org

It is also possible to export vector graphics to EPS format using OpenOffice.org Draw, which is an open source office suite available for Windows, Linux and Mac.

TpX

Vector editor TpX separates geometric objects from text objects. Geometric objects are saved into .PDF file, the rest is saved in .TpX file to be processed by LaTeX. User just create the graphics in TpX editor and calls the .TpX file from latex file by command \input{...TpX}.

Xfig

Xfig is a basic program that can produce vector graphics, which can be exported to LaTeX. It can be installed on Unix platforms.

On Microsoft Windows systems, Xfig can only be installed using Cygwin-X; however, this will require a fast internet connection and about 2 gigabytes of space on your computer. With Cygwin, to run Xfig, you need to first start the "Start X - Server", then launch "xterm" to bring up a terminal. In this terminal type "xfig" (without the quotation marks) and press return.

Alternatively, WinFIG is an attempt to achieve the functionality of xfig on Windows computers.

There are many ways to use xfig to create graphics for LaTeX documents. One method is to export the drawing as a LaTeX document. This method, however, suffers from various drawbacks: lines can be drawn only at angles that are multiples of 30 and 45 degrees, lines with arrows can only be drawn at angles that are multiples of 45 degrees, several curves are not supported, etc.

Exporting a file as PDF/LaTeX or PS/LaTeX, on the other hand, offers a good deal more flexibility in drawing. Here's how it's done:

1. Create the drawing in xfig. Wherever you need LaTeX text, such as a mathematical formula, enter a LaTeX string in a textbox.
2. Use the Edit tool to open the properties of each of those textboxes, and change the option on the "Special Flag" field to Special. This tells LaTeX to interpret these textboxes when it opens the figure.
3. Go to File -> Export and export the file as PDF/LaTeX (both parts) or PS/LaTeX (both parts), depending on whether you are using pdflatex or pslatex to compile your file.
4. In your LaTeX document, where the picture should be, use the following, where "test" is replaced by the name of the image:
 \begin{figure}[htbp]  \centering  \input{test.pdf_t}  \caption{Your figure}  \label{figure:example} \end{figure}

Observe that this is just like including a picture, except that rather than using \includegraphics, we use \input. If the export was into PS/LaTeX, the file extension to include would be .pstex_t instead of .pdf_t.

5. Make sure to include packages graphicx and color in the file, with the \usepackage command right below the \documentclass command, like this:
 \usepackage{graphicx} \usepackage{color}

And you're done!

For more details on using xfig with LaTeX, this chapter of the xfig User Manual may prove helpful.

Other tools

Commercial vector graphics software, such as Adobe Illustrator, CorelDRAW, and FreeHand are commonly used and can read and write EPS figures. However, these products are limited to Windows and Mac OS X platforms.

### Raster graphics

It can save to EPS.

GIMP

GIMP, has a graphical user interface, and it is multi-platform. It can save to EPS and PDF.

### Plots and Charts

Generic Mapping Tools (GMT)

Generic Mapping Tools (GMT), maps and a wide range of highly customisable plots.

Gnumeric

Gnumeric, spreadsheets has SVG, EPS, PDF export

Gnuplot

Gnuplot, producing scientific graphics since 1986. If you want to make mathematical plots, then Gnuplot can save in any format. You can get best results when used along PGF/TikZ.

matplotlib

matplotlib, plotting library written in python, with PDF and EPS export. On the other hand there is a PGF export also. There are some tricks to be able to import formats other than EPS into your DVI document, but they're very complicated. On the other hand, converting any image to EPS is very simple, so it's not worth considering them.

R

R, statistical and scientific figures.

### Editing EPS graphics

As described above, graphics content can be imported into LaTeX from outside programs as EPS files. But sometimes you want to edit or retouch these graphics files. An EPS file can be edited with any text editor since it is formatted as ASCII. In a text editor, you can achieve simple operations like replacing strings or moving items slightly, but anything further becomes cumbersome. Vector graphics editors, like Inkscape, may also be able to import EPS files for subsequent editing. This approach also for easier editing. However, the importing process may occassionally modify the original EPS image.

## Notes and References

1. Johan B. C. Engelen. "How to include an SVG image in LATEX". mirrorcatalogs.com.
2. Philip Ilten. "The svg-package on CTAN". ctan.org.