Chapter 10. Graphics Generation and Manipulation

TeX probably has the best algorithm for formatting paragraphs and building pages from them. But in this era of ever-increasing information exchange, most publications do not limit themselves to text—the importance of graphical material has grown tremendously. TeX by itself does not address this issue, as it deals only with positioning (black) boxes on a page. Knuth, however, provided a hook for implementing “features” that are not available in the basic language, via the special command. The latter command does not affect the output page being formatted, but TeX will put the material, specified as an argument in the special command, literally at the current point in the .dvi file.1 The dvi driver then has to interpret the received information and produce the output image accordingly (see also [144]).

1 In certain situations the special command may change the formatting because it can produce an additional breakpoint and it might prevent LaTeX from noticing spaces.

The LaTeX Graphics Companion [57, Chapter 1] describes in detail various approaches that can be used to produce graphics with TeX. The following list gives a short overview. Interested readers are referred to that book for more details.

1. ASCII drawing, such as PiCTeX, which provides a complete plotting language where most graphical elements are implemented by combining a very large number of small dots.

2. Picture-element fonts, such as LaTeX’s picture environment. Kristoffer Rose’s xypic system [57, Chapter 5] uses special fonts to typeset diagrams.

3. Picture macro packages, mainly based on the picture environment or on TeX’s raw line-drawing commands. Among others, packages exist for drawing chemical formulae [57, Section 6.2], trees, and bar charts (see Section 10.1.6).

4. Picture fonts, where each character to be typeset is one, possibly enormous, “letter” in a font. One can use or MetaPost for generating the pictures [57, Chapter 3], or else use already existing bitmaps and transform them into a .pk file directly [57, Section 1.3].

5. Half-tone fonts—blocks consisting of various levels of grey, which can be combined in the normal TeX way to generate pictures [39, 93].

6. Graphics material included via the special command. This approach is by definition device dependent, as it relies on the possibilities of the dvi driver and the output device. The graphics package, described in Section 10.2, offers a higher-level support layer on top of TeX’s special command. This approach has become very common because of the wide availability of low-cost PostScript printers and previewers. Other high-level systems allowing one to use PostScript together with LaTeX are psfrag and pstricks [57, Chapter 4].

In this chapter we look at techniques for producing portable graphics (mainly based on item 3) and at the high-level interface to device-dependent graphics support (item 6).

In particular, the first section discusses LaTeX’s built-in graphics tools. We look at how to build ornaments, which can be useful for making important material stand out. Then we turn our attention to two packages, epic and eepic, that extend the picture environment by introducing a set of new commands. They are described in detail and examples show how they are used in practice.

LaTeX2ε provides a generalized driver-independent interface to include external graphic material and to scale and rotate LaTeX boxes.1 Section 10.2 deals with graphics file inclusion. For this LaTeX offers both a simple interface (graphics; see Section 10.2.2), which can be combined with the separate rotation and scaling commands, and a more complex interface (graphicx; see Section 10.2.3), which has its own powerful set of image manipulation options. Free-standing scaling and rotation is the subject of Section 10.3.

1 A generalized package for color is also available; see the LaTeX Manual [104] for more details.

In the final section we say a few words about important display languages (PostScript, PDF, SVG). We also briefly discuss dvips, an often-used dvi to PostScript translation program, and describe pspicture, an extension of LaTeX’s picture environment that uses PostScript drawing primitives interfaced to the dvips driver.

10.1. Producing portable graphics and ornaments

Portable graphics in LaTeX essentially mean graphics built from boxes, lines, and characters. LaTeX boxes are reviewed briefly in Appendix A.2. Here, we first present packages that provide extensions to the usual LaTeX boxes. Later, this section deals with line graphics.

10.1.1. boxedminipage—Boxes with frames

The boxedminipage environment, defined in the boxedminipage package (by Mario Wolczko), behaves like the standard minipage environment, but the result is surrounded by a frame, as if it was placed inside an fbox. The thickness and separation of the rules are controlled by the fboxrule and fboxsep parameters, respectively. However, in contrast to a construction involving fbox, one can use verbatim commands inside the environment body.

10-1-1
Image

10.1.2. shadow—Boxes with shadows

The shadow package (by Mauro Orlandini) defines the shabox command. It is similar to the LaTeX command fbox, except that a “shadow” is added to the bottom and the right side of the box.

Three parameters control the visual appearance of the box (defaults are given in parentheses): sboxrule defines the width of the lines for the frame (0.4pt); sboxsep defines the separation between the frame and the text (10pt); and sdim specifies the dimension of the shadow (4pt).

10-1-2
Image

10.1.3. fancybox—Ornamental boxes

Timothy Van Zandt, in the framework of his seminar package for producing slides, developed the fancybox package. It introduces various new commands for boxing and framing data in LaTeX. In this section we review only a few of the more basic commands. More information can be found in the documentation accompanying the seminar package.

The package introduces four variants for the fbox command. As with the fbox command, the distance between the box and the frame is given by the length parameter fboxsep (LaTeX’s default is 3pt). Other parameters governing these boxes are described below.

The shadowbox command adds a shadow with width shadowsize (default 4pt). The box is aligned at the base of the shadow, which makes it probably less suitable for inline usage than the shabox command described earlier. Notice the different spacing defaults.

10-1-3
Image

The ovalbox command generates a frame with rounded corners. The width of the frame is the same as that produced by standard picture elements when the hinlines declaration is in effect. The Ovalbox command is similar but has a frame width corresponding to the size produced by a hicklines declaration. The diameter of the corner arcs is set with a cornersize declaration. The form cornersize{num} sets the diameter to num × minimum (width of box, height of box); the form cornersize*{len} sets the diameter to the length len. The default is cornersize{0.5}.

10-1-4
Image

The package also provides fancyoval as an alternative to LaTeX’s oval picture command. While oval always makes the diameter of the corner arcs as large as possible, fancyoval uses the cornersize declaration to set the diameter.

10-1-5
Image

Finally, the package offers the doublebox command, which generates two square frames. Their widths and relations to each other and the text are fractions of the fboxrule parameter value: the width of the inner frame is 0.75 of fboxrule and that of the outer frame is 1.5 of fboxrule. The distance between the two frames is 1.5 of fboxrule plus 0.5pt.

10-1-6
Image

None of the above commands have optional arguments, unlike framebox and makebox. You can get exactly the same functionality by using makebox in the argument of these framing commands.

10-1-7
Image

For some types of documents, such as slides, it would be nice to allow for framed pages—that is, to apply commands like those introduced in this section as part of the page style. This capability is supported by the fancybox package through the declaration fancypage{inner}{outer}. The completed page, before headers and footers are added, is boxed (so it has width extwidth and height extheight) and then passed to the code specified in inner as an argument. Next the headers and footers are added using the new width of the page, in case it is changed by inner. The result is passed as an argument to the code in outer, which again expects one argument. Thus, in the simplest case, you could specify one of the boxing commands from this section, or even leave one of the arguments empty. The next example shows an application where the arguments also contain some parameter settings to influence the form of the added frames.

10-1-8
Image

Incorrect running headers or footers

Notice that the position of the running header was automatically corrected to fit the extended text width covering the frame. However, this correction works only for standard page styles. If, for example, fancyhdr is used, then the resulting headers and footers will be too small, as this package uses its own method of producing these objects.

10-1-9
Image

In the case of fancyhdr, the problem can be corrected by adding an extra offset with fancyhfoffset. The value of 20.8pt was manually calculated as twice the separation between text and frame (10pt) and the width of the frame line (0.4pt).

Caveats

The fancypage declaration is applied to all pages starting with the current one until another fancypage declaration appears within the document. If you want to add frames only to the current page, use hisfancypage instead. “Current” in this context means the page under construction when the declaration is first seen by LaTeX, even if that point in the document later ends up on a different page. Thus, it behaves like pagestyle in this respect. If problems arise, you either have to move the declaration to some earlier or later point in the document or stop LaTeX from looking too far ahead by adding a pagebreak command somewhere before the declaration.

The other potential problem with the commands hisfancypage and fancypage is that they change LaTeX’s output routine and, therefore, may not work with other packages that do the same (fancyhdr is an example, though, with some care, both packages can coexist). Also, bad arguments can cause serious errors, which generate uninformative error messages.

Image

A somewhat more powerful way to add material to every page in fixed locations is provided by the fancyput declaration. It has a syntax similar to LaTeX’s put command, but requires the specification of dimensions for the x and y coordinates. The origin (0pt,0pt) is one inch from the top and left of the paper. Thus, to put something two inches from the left and three inches from the top, you would specify (1in,-2in).

10-1-10
Image

The variant form hisfancyput affects only the current page, analogous to hisfancypage. If the starred form is used (for either command), then, instead of replacing it, the new material is added to existing material previously inserted with fancyput or hisfancyput.

Boxed display environments

The package also predefines boxed versions of the standard LaTeX display environments. The size of the resulting box is determined by the longest line. All environments support an optional argument for positioning the box in relation to the objects on the line; it can be t for top alignment or b for bottom alignment, but the default is to center the box.

The environments Bcenter, Bflushleft, and Bflushright generate a box with the contents centered, flushleft, and flushright, respectively. The example shows all of them in action. Note the use of vspace to ensure that the outer Bflushleft box is bottom aligned. Compare this to the examples discussed in Section A.2.2 on page 862.

10-1-11
Image

Bitemize, Benumerate, and Bdescription implement boxed versions of the itemize, enumerate, and description environments, respectively. The internal implementation uses LaTeX’s tabular environment, which means that vertical-mode material such as vspace does not work. Instead, the item command takes an optional argument (using parentheses!) to specify extra white space in front of the item. Its usage is shown in the next example.

For math applications, Beqnarray produces a boxed environment similar to that created by eqnarray, but the equation number always comes out on the right. Beqnarray* is like eqnarray*, but the generated box is just large enough to hold all the equations. An optional position argument is not supported.

10-1-12
Image

The package also reimplements several commands to typeset verbatim texts. For such applications, however, the fancyvrb package by the same author provides superior interfaces (see Section 3.4.3).

10.1.4. epic—An enhanced picture environment

Standard LaTeX provides a picture environment that allows you to generate line-style graphics of arbitrary complexity through basic commands for drawing lines, vectors, quarter-circles, and Bézier curves. Thus, creating complex graphics, although possible, requires a lot of manual effort. Most of these picture-drawing commands require explicit specification of coordinates for every object. Using higher-level commands can reduce the number of coordinates that need to be manually calculated. Basically, two approaches can be taken to the design of such commands:

• A set of objects can be selected so that the entire set can be plotted by specifying one or two coordinate pairs—the shortstack command falls under this approach.

• Commands are provided that will do most of the computations internally and require only simple coordinate pairs to be specified—the multiput command is an example of this approach.

The obvious advantage of using commands that implement these approaches is not only that they are easier to specify initially, but any subsequent modification to the layout requires minimal recalculations.

The frequently used primitive command line has severe limitations and drawbacks. Its arguments are very nonintuitive and require extensive calculations. Often the thought process in writing a line command involves several steps:

1. Calculating the coordinates of the two end points

2. Calculating the horizontal and vertical distance

3. Translating these distances into an (x, y) pair for specifying a slope and a horizontal distance for specifying the length of the line

4. Determining whether the desired slope is available and, if not, repeating steps 1 through 3 until a satisfactory slope is achieved

This mechanism is very cumbersome. Moreover, the length of the shortest available line at different slopes is not the same due to the way that the line command is implemented. To overcome these difficulties, the epic package (by Sunil Podar) provides a powerful high-level user interface to the picture environment [139]. Its main aim is to reduce the amount of manual calculations required to specify the layout of objects. In this way, the epic package makes it possible to produce sophisticated pictures with less effort than before.

High-level line commands

The package introduces a number of powerful line-drawing commands, while at the same time providing a simpler syntax. In particular, these commands take only the coordinates of the end points, thus eliminating the other steps involved in specifying a line.

Image

The dottedline command connects the specified points by drawing a dotted line between each pair of coordinates. At least two points must be defined. The dotted line is drawn with an inter-dot gap as specified in the mandatory argument dotgap (in unitlength). Because the number of dots to be plotted must be an integer, the inter-dot gap may not come out exactly as specified.

10-1-13
Image

By default (i.e., if no optional dotchar argument is used), dottedline plots tiny squares, produced internally by the picsquare command. The size of the squares depends on the current setting of the hinlines, hicklines, or linethickness command. In fact, most of the epic commands internally use picsquare for plotting lines.

By using the optional dotchar argument, you can plot any object along the line specified by the coordinates. Note that some characters like “*” in the Roman font do not come out centered, although most other characters and objects do.

10-1-14
Image
Image

The dashline command connects the specified points by drawing a dashed line between each pair of coordinates. At least two points must be specified. Internally, each dash is constructed using the dottedline command. The mandatory parameter dashlength determines the length of each dash, and the optional argument dashdotgap gives the gap between the dots that are used to construct the dash, both in unitlength terms. By default, a solid-looking dash is constructed.

10-1-15
Image

In the definition of the dashline command, the optional stretch parameter must be an integer between -100 and . It indicates the percentage by which the number of dashes is “stretched” or increased (stretch > 0) or is “shrunk” or reduced (stretch < 0). If stretch is zero, the minimum number of dashes compatible with an approximately equal spacing relative to the empty space between the dashes is used. The idea behind the stretch percentage parameter is that if several dashed lines of different lengths are being drawn, then all dashed lines with identical stretch values will have a similar visual appearance. The default settings for the stretch percentage can be changed by redefining the command dashlinestretch:

Image

Its value defines the increase or reduction that will be applied to all subsequent dashline commands except for those where the stretch parameter is explicitly specified as the first optional argument.

Image

Unwanted jagged lines

The drawline command connects the given points by drawing a line between each pair of coordinates using line segments of the closest slope available in the line fonts of LaTeX. A minimum of two points must be specified. Only a finite number of slopes are available in the line segment fonts, so unavailable slopes are produced by repeatedly using very short line segments of a nearby slope. As a consequence, some lines may appear jagged (in the next example all sloped lines show this effect). This is the price you must pay for being allowed to implicitly specify lines of any slope. However, the problem vanishes if the eepic package is used in addition to epic.

A drawline command can generate thick or thin lines depending on the setting of the hinlines or hicklines parameters in effect. These are the only two thicknesses available for such lines.

The optional stretch parameter is similar to the one described for the dashline command. If stretch is zero, the result is the minimum number of dashes required to make the line appear solid, with each dash being “connected” at the ends. If stretch is greater than zero, more dashes are used in constructing the line, giving a less jagged appearance (compare the two houses in the example).

10-1-16
Image

As with the dashlinestretch parameter and the dashline command, the parameter drawlinestretch allows you to set the default value for the stretch percentage parameter of the drawline command.

Plotting scientific data

When presenting scientific data, it is often desirable to produce graphs that show obtained (two-dimensional) data sets in relation to each other. One representation strategy is to plot one set of experimentally obtained data points using a certain type of graphical representation (e.g., filled circles) and another using some different symbol (e.g., diamonds). For further clarification you might want to join the individual data points with some kind of line, perhaps using different types of “lines” to help the reader distinguish between the resulting curves.

One way to achieve this result is to plot the experimental results using a sequence of basic put statements, followed by a dottedline, dashline, or drawline command, that connects the data points. In other words, you specify the coordinates twice. To facilitate this process, epic offers the three environments dottedjoin, dashjoin, and drawjoin corresponding to the above commands and accepting the same optional and mandatory arguments. These environments use the new command jput (join and put), which is identical to the regular put command of LaTeX except that it can be used inside these three environments only. All objects put within the scope of any of the three environments via a jput command are, in addition to being plotted, joined by lines of their respective type. It is up to the user to center the objects at the plotted points.

An instance of any of the three ..join environments defines a separate “curve”; hence, every set of points belonging to a different “curve” should be enclosed in a separate ..join environment. The prime motivation for designing the ..join environments was to allow for plotting graphs that use different types of curves and dissimilar lines.

10-1-17
Image

Loading externally generated graphic data

Another way to produce graphs that is offered by the epic package is through the putfile{file}{object} command. It is similar to LaTeX’s put command, except that the x and y coordinates required by the put command are read from an external file and the same object is plotted at each of those coordinates. This command is provided because TeX lacks the capability of doing floating-point arithmetic, which is required if you wish to plot a parametric curve different from a straight line. The coordinates of points on such curves can easily be generated by a program in some computer language and subsequently read in by TeX. The external file must contain the (x, y) coordinate pairs, one pair per line, with a space between the two coordinates. The % is available as a comment character, but you should leave at least one space following the y entry if a comment appears on the same line as data because a % masks the newline character.

For example, to plot a smooth curve along a set of coordinates, you can use the following procedure:

1. Create a file with the x, y coordinates of the data points, which you might call plot.data, for example.

2. If you wish, smooth the data.

3. Place the following code inside a picture environment in your LaTeX file: putfile{plot.data}{picsquare}

As the command name indicates, putfile uses put and not jput. This choice is unfortunate, as it means that using putfile inside one of the ..join environments will plot objects at the coordinates but not connect them, even though there is technically nothing to prevent this connection. There is, however, a small trick you can use if you are interested in creating such linkage: ensure that put always executes jput inside your pictures. Because jput behaves exactly like LaTeX’s put command if used outside the ..join environments, there is no harm in making this a global substitution. This approach is used in the next example.

10-1-18
Image
Placing objects at regular intervals

What is missing in the example graphs so far are labeled axes. The epic package doesn’t offer off-the-shelf commands to do the full job, but with multiputlist and grid it offers tools that can help you with the more tedious tasks.

Image

This command is a variant of LaTeX’s multiput command, which allows the same object to be placed at regularly spaced coordinates. The multiputlist command is similar, but permits the objects to be different. When the multiputlist command is executed, the objects to be “put” are picked up from the list of items, as the coordinates are incremented. (The first item goes in position 1, the second item in position 2, and so on.) For example, you can plot numbers along the x-axis in a graph by specifying

Image

The objects in the list can be virtually anything, including makebox, framebox, or math characters. This command enforces a certain regularity and symmetry on the layout of the various objects in a picture.

Image

The grid command makes a grid of dimensions width units by height units. Vertical lines are drawn at intervals of Δwidth and horizontal lines at intervals of Δheight. When the third (optional) argument is specified, the borders of the grid will be labeled with numbers whose starting values are the integer numbers initial-X-int and initial-Y-int, respectively. They will be incremented by Δwidth and Δheight along the axes.

The grid command produces a box. Therefore, it must be put at the required coordinates. For example:

10-1-19
Image

If you need more flexibility than that offered by grid for producing a regular two-dimensional structure, then matrixput might offer the answer.

Image

This command is the two-dimensional equivalent of the primitive LaTeX command multiput. It is more efficient, however, to use matrixput than multiple multiput statements. This command is especially useful for drawing pictures where a pattern is repeated at regular intervals in two dimensions.

10-1-20
Image

10.1.5. eepic—Extending the epic package

LaTeX provides a basic but limited picture-drawing capability, which is extended by commands for drawing solid lines, dotted lines, dashed lines, and new environments suitable for plotting graphs of the epic package (described in the previous section). However, epic inherits many of LaTeX’s limitations in picture drawing. As a result, some of the functions take a long time to accomplish or the output is not of very high quality. In LaTeX, special fonts are used to draw lines and circles. For this reason only lines with certain slopes are supported and only a limited set of diameters is available when drawing circles, ovals, or disks.

The following example shows some of these limitations. Here, the circle and disk on the left are too small (without producing any warning) and the line commands produce errors because the required slope is not available. Loading epic does not help in this case.

10-1-21
Image

Compare this result to Example 10-1-22 on the next page, which shows the correct output—it is strikingly different.

At the end of the 1980s, the pic programming language was developed to provide a “natural language” method of describing simple pictures and graphs (see [77]). A preprocessor, like GNU’s gpic, can translate these graphics commands into output that the UN*X formatter, troff, understands. More interestingly for us, it can also generate TeX special commands, which many dvi driver programs support. For instance, the dvips dvi-to-PostScript translator, described in Section 10.4.2, can interpret these commands.

The eepic package, written by Conrad Kwok, is an extension of both LaTeX and epic that overcomes some of the limitations in LaTeX, epic, and gpic by generating gpic specials using TeX commands. Because eepic is a superset of epic, you can use it to process any picture that relies on epic commands and get better-looking output.

eepic’s reimplementation of LaTeX commands

The extensions in eepic allow users to draw lines having any slope and to draw circles of any size. However, the limitation of slopes for vectors remains the same. Thus, the only slopes that can be handled are of the form x/y, where x and y are integers in the range [-4, 4].

Image

The syntax of the line command is the same in eepic as in LaTeX. Now, however, x and y can be any integers acceptable to TeX. Furthermore, there is no longer a lower limit for the length parameter (about 3.5mm in standard LaTeX).

Image

The syntax for drawing hollow and filled circles, circle and circle*, is the same as that in LaTeX. Now, however, the diameter parameter can be any number acceptable to TeX, and a circle with a diameter of (exactly) the specified value will be drawn. The oval command has been modified so that the maximum diameter of the quarter-circles at the corners can be set to any value by setting the variable maxovaldiam to the desired TeX dimension (default 40pt).

The following example repeats Example 10-1-21 on the facing page, except that now eepic has been loaded and maxovaldiam has been used. All elements appear as specified in the revised example.

10-1-22
Image
eepic’s reimplementation of epic commands

The epic package generates standard dvi files and requires the presence of only the standard LaTeX fonts. The eepic package, as an extension to epic, offers better line-drawing output, provides faster operation, and requires less memory. It reimplements the drawline, dashline, and dottedline commands (see page 601) and the corresponding ..join environments, dashjoin, dottedjoin, and drawjoin (see page 604).

Compare the diagonal lines in the following example with those in Example 10-1-16 on page 604. Note that when eepic is loaded in conjunction with epic it smoothes the result of any line-drawing command. Both packages must be loaded in the right order.

10-1-23
Image

The eepic package also introduces a number of new commands. Apart from the path command, these commands do not have equivalents in LaTeX and epic. The end of this section discusses portability issues as they relate to these packages.

Image

The allinethickness command sets the line thickness of all line-drawing commands, including lines in slopes, circles, ellipses, arcs, ovals, and splines.

After issuing Thicklines, the thickness of all subsequently drawn lines will be about 1.5 times greater than that with hicklines.

Image

The path command is a fast version of the drawline command. The optional stretch argument of the latter command is not allowed, so path draws only solid lines. This command is mainly used for drawing complex paths.

Image

The spline command draws a Chaikin’s curve that passes through only the first and last points. All other points act as control points only.

Image

In analogy to the circle and circle* commands, the ellipse and ellipse* commands draw a hollow or filled ellipse using the specified x-diameter and y-diameter parameters.

Image

The arc command draws a circular arc. The first parameter, diameter, is given in unitlength terms. Both start-angle and end-angle are in radians; start-angle must lie within the interval Image, and end-angle can be any value between start-angle and start-angle + 2π. Arcs are drawn clockwise, with the angle 0 pointing to the right on the paper.

Image

The filltype command specifies the type of area fill for the circle* and ellipse* commands. The instruction itself does not draw anything, but merely changes the interpretation of * in the two commands specified above. Possible values for area-fill-type are black (default), white, and shade. For example, you can change the area fill type to white with filltype{white}.

Portability issues

The eepic package is not necessarily available at all LaTeX sites or, even if it is available, it may not be supported by the chosen output device. To avoid the portability problems that can arise from its use, and at the same time take advantage of eepic’s more precise printout, take the following precautions:

• Do not use line commands, but use drawline instead. The line command in LaTeX supports only a limited set of slopes.

• Do not use the arc command. Use the command spline if a complex curve is really necessary.

• Avoid using solid or small inter-dot gaps in drawing long dashed lines, as these need a lot of TeX memory in the original epic implementation. Use the drawline command with negative stretch to draw dashed lines.

Emulating the eepic commands

If your installation does not support eepic but you have to print your document, then you should use the eepic emulation macros defined with the eepicemu package. The extended commands are emulated in the following ways:

• Circles larger than 40pt are drawn using oval.

• Ellipses are drawn using oval.

• Arcs generate a warning but are ignored otherwise.

• Splines are approximated with drawline.

path is substituted by drawline.

Thicklines is substituted by hicklines.

allinethickness is substituted by hicklines and linethickness.

Because the eepic package redefines several commands of the epic package, the eepic package declaration must follow the epic package declaration. Although not strictly necessary, it is good practice to always include epic when using eepic commands. In any case, the eepic emulation package eepicemu will work only when both are specified.

10.1.6. Special-purpose languages

Building on LaTeX’s picture environment, possibly extended with the epic and eepic packages, several package authors have implemented high-level user interfaces intended to make entering graphical information more straightforward and less error prone by adopting a syntax that is more familiar to the end user in a particular application domain. Some of the systems are quite complex (The Graphics Companion [57] describes several of them in detail). In this section we merely give a flavor of what is possible in this area by showing a few short examples.

If you do not have access to a drawing package but need to include a few continuously sloping curves, the curves package written by I. L. Maclaine-cross offers some intriguing features. It allows you to vary curve thickness over a large range, to control end slopes, and to specify closed curves with continuous slopes. It can also build large circles and circular arcs with arc, providing independent scaling of curve abscissa and ordinates to fit graphs. Furthermore, it offers affine scaling for making arcs or circles become elliptical and it supports symbols and dash patterns. In the simple example that follows, curve draws a curve through the specified coordinate pairs, closecurve draws a closed curve with continuous tangents at all points, and agcurve generally acts like curve except that the first and last segments are not drawn.

10-1-24
Image

Hideki Isozaki’s ecltree package allows you to draw simple tree structures. It offers a bundle environment for labeling a top node, which can contain one or more down nodes defined by chunk commands, whose optional argument can be used to add comments on a line. The drawwith command allows you to control the line style by specifying as an argument one of epic’s line-drawing commands (described in Section 10.1.4). The bundle environment and chunk commands can be nested, as shown in the following LaTeX code.

10-1-25
Image

The bar package was written by Joachim Bleser and Edmund Lang to produce bar charts. A barenv environment encloses the data defining a bar chart. Each data point is specified using a ar command, whose two mandatory arguments give the ordinate of the entry and the hatching type. The package also offers quite a few set... commands to fine-tune the presentation of the information, as shown in the example that follows.

10-1-26
Image

As already stated, much more complex structural data can be entered in a convenient way by using a dedicated package. One example is Shinsaku Fujita’s XyMTeX bundle for drawing chemical diagrams (see [48, 49] or [57, Chapter 6]). By using command names inspired by standard nomenclature known to practitioners in the field, complex formulas can be entered simply. In the following example, we use the hetarom subpackage, designed for specifying the structure of vertical heterocyclic compounds.

10-1-27
Image

10.2. LaTeX’s device-dependent graphics support

Since the introduction of LaTeX2ε in 1994, LaTeX has offered a uniform syntax for including every kind of graphics file that can be handled by the different drivers. In addition, all kinds of graphic operations (such as resizing and rotating) as well as color support are available.

These features are not part of the LaTeX2ε kernel, but rather are loaded by the standard, fully supported color, graphics, and graphicx extension packages. As the TeX program does not have any direct methods for graphic manipulation, the packages have to rely on features supplied by the “driver” used to print the dvi file. Unfortunately, not all drivers support the same features, and even the internal method of accessing these extensions varies among drivers. Consequently, all of these packages take options such as dvips to specify which external driver is being used. Through this method, unavoidable device-dependent information is localized in a single place, the preamble of the document.

The packages graphics and graphicx can both be used to scale, rotate, and reflect LaTeX material, or to include graphics files prepared with other programs. The difference between the two is that graphics uses a combination of macros with a “standard” or TeX-like syntax, while the “extended” or “enhanced” graphicx package presents a key/value type of interface for specifying optional parameters to the includegraphics and otatebox commands.

10.2.1. Options for graphics and graphicx

When using LaTeX’s graphics packages, the necessary space for the typeset material after performing a file inclusion or applying some geometric transformation is reserved on the output page. It is, however, the task of the device driver (e.g., dvips, xdvi, dvipsone) to perform the actual inclusion or transformation in question and to show the correct result. As different drivers require different code to carry out an action like rotation, one has to specify the target driver as an option to the graphics packages—for example, option dvips if you use one of the graphics packages with Tom Rokicki’s dvips program, or option textures if you use one of the graphics packages and work on a Macintosh using Blue Sky’s Textures program.

Some drivers, such as previewers, are incapable of performing certain of the desired functions. Hence, they may display the typeset material so that it overlaps with the surrounding text. Table 10.1 on the facing page shows the drivers currently supported and their possible limitations. Support for other drivers is added occasionally, so it is worth checking the online documentation of the package for a driver not listed in this table.

Image

Table 10.1. Overview of color and graphics capabilities of device drivers

The driver-specific code is stored in files with the extension .def—for example, dvips.def for the PostScript driver dvips. As most of these files are maintained by third parties, the standard LaTeX distribution contains only a subset of the available files and not necessarily the latest versions. While there is usually no problem if LaTeX is installed as part of a full TeX installation, you should watch out for incompatibilities if you update the LaTeX graphics packages manually.

Setting a default driver

It is also possible to specify a default driver using the ExecuteOptions declaration in the configuration file graphics.cfg. For example, the declaration ExecuteOptions{emtex} makes the emTeX drivers become the default. In this case the graphics packages pick up the driver code for the emTeX TeX system on a PC if the package is called without a driver option. These days most TeX installations are distributed with a ready-to-use graphics.cfg file.

In addition to the driver options, the packages support some options controlling which features are enabled (or disabled):

draft Suppress all “special” features, such as including external graphics files in the final output. The layout of the page will not be affected, because LaTeX still reads the size information concerning the bounding box of the external material. This option is of particular interest when a document is under development and you do not want to download the (often huge) graphics files each time you work on it. When draft mode is activated, the picture is replaced by a box of the correct size containing the name of the external file.

final The opposite of draft. This option can be useful when, for instance, “draft” mode was specified as a global option with the documentclass command (e.g., for showing overfull boxes), but you do not want to suppress the graphics as well.

hiresbb In PostScript files look for bounding box comments that are of the form %%HiResBoundingBox (which typically have real values) instead of the standard %%BoundingBox (which should have integer values). With the graphicx package, this and the previous options are also available locally for individual includegraphics commands.

hiderotate Do not show the rotated material (for instance, when the previewer cannot rotate material and produces error messages).

hidescale Do not show the scaled material (for instance, when the previewer does not support scaling).

10.2.2. The includegraphics syntax in the graphics package

With the graphics package, an image file can be included by using the following command:

Image

If the [urx, ury] argument is present, it specifies the coordinates of upper-right corner of the image as a pair of TeX dimensions. The default units are big (PostScript) points; thus, [1in,1in] and [72,72] are equivalent. If only one optional argument is given, the lower-left corner of the image is assumed to be located at [0,0]. Otherwise, [llx,lly] specifies the coordinates of that point. Without optional arguments, the size of the graphic is determined by reading the external file (containing the graphics itself or a description thereof; see below).

The starred form of the includegraphics command “clips” the graphics image to the size of the specified bounding box. In the normal form (without the *), any part of the graphics image that falls outside the specified bounding box overprints the surrounding text.

The examples in the current and next sections use a small PostScript program (in a file w.eps) that paints a large uppercase letter “W”, and a few lines. Its source is shown in Figure 10.1. Note the BoundingBox declaration, which stipulates that the image starts at the point 100, 100 (in big points), and goes up to 150, 150; that is, its natural size is 50 big points by 50 big points.

Image

Figure 10.1. The contents of the file w.eps

In the examples we always embed the includegraphics command in an fbox (with a blue frame and zero fboxsep) to show the space that LaTeX reserves for the included image. In addition, the baseline is indicated by the horizontal rules produced by the HR command, defined as an abbreviation for ule{1em}{0.4pt}.

The first example shows the inclusion of the w.eps graphic at its natural size. Here the picture and its bounding box coincide nicely.

10-2-1
Image

Next, we specify a box that corresponds to a part of the picture (and an area outside it) so that some parts fall outside its boundaries, overlaying the material surrounding the picture. If the starred form of the command is used, then the picture is clipped to the box, as shown on the right.

10-2-2
Image

In the remaining examples we combine the includegraphics command with other commands of the graphics package to show various methods of manipulating an included image. (Their exact syntax is discussed in detail in Section 10.3.) We start with the scalebox and esizebox commands. In both cases we can either specify a change in one dimension and have the other scale proportionally, or specify both dimensions to distort the image.

10-2-3
Image
10-2-4
Image

Adding rotations makes things even more interesting. Note that in comparison to Example 10-2-1 on the preceding page the space reserved by LaTeX is far bigger. LaTeX “thinks” in rectangular boxes, so it selects the smallest size that can hold the rotated image.

10-2-5
Image

10.2.3. The includegraphics syntax in the graphicx package

The extended graphics package graphicx also implements includegraphics but offers a syntax for including external graphics files that is somewhat more transparent and user-friendly. With today’s TeX implementations, the resultant processing overhead is negligible, so we suggest using this interface.

Image

The starred form of the command exists only for compatibility with the standard version of includegraphics, as described in Section 10.2.2. It is equivalent to specifying the clip key.

The key/val-list is a comma-separated list of key=value pairs for keys that take a value. For Boolean keys, specifying just the key is equivalent to key=true; not specifying the key is equivalent to key=false. Possible keys are listed below:1,2

1 Kept for backward compatibility only. [bbllx=a, bblly=b, bburx=c, bbury=d] is equivalent to [bb = a b c d], so the latter form should be used.

2 These arguments can be used for setting the lower-left coordinate to (0 0) and the upper-right coordinate to (natwidth natheight) and are thus equivalent to bb=0 0 w h, where w and h are the values specified for these two parameters.

Image
Image

If the size is given without units for the first eight keys (bb through trim), then TeX’s “big points” (equal to PostScript points) are assumed.

The first ten keys (bb through natwidth) specify the size of the image. This information needs to be given in case TeX cannot read the file, the file contains incorrect size information, or you wish to clip the image to a certain rectangle.

The next seven keys (angle through scale) have to do with scaling or rotation of the included material. Similar effects can be obtained with the graphics package and the includegraphics command by placing the latter inside the argument of a esizebox, otatebox, or scalebox command (see the examples in Section 10.2.2 and the in-depth discussion of these commands in Section 10.3).

It is important to note that keys are read from left to right, so that [angle=90, totalheight=2cm] means rotate by 90 degrees and then scale to a height of 2 cm, whereas [totalheight=2cm, angle=90] would result in a final width of 2 cm.

By default, LaTeX reserves for the image the space specified either in the file or in the key/val-list. If any part of the image falls outside this area, it will overprint the surrounding text. If the starred form is used or the clip option is specified, any part of the image outside this area is not printed.

The last four keys (type, ext, read, command) suppress the parsing of the file name. When they are used, the main file argument should have no file extension (see the description of the DeclareGraphicsRule command below).

Below we repeat some of the examples from Section 10.2.2 using the syntax of the graphicx package, showing extra facilities offered by the extended package. In most cases the new form is easier to understand than the earlier version. In the simplest case without any optional arguments, the syntax for the includegraphics command is the same in both packages.

If we use the draft key, we get just a frame showing the bounding box. This feature is not offered by the graphics package on the level of individual graphics.

10-2-6
Image

The effects of the bb, clip, viewport, and trim keys are seen in the following examples. Compare them with Example 10-2-2 on page 617.

10-2-7
Image

Using viewport or trim allows us to specify the desired result in yet another way. Notice that we actually trim a negative amount, effectively enlarging the space reserved for the picture.

10-2-8
Image

If you want to apply a scale factor to the image, use the scale key. With this key, however, you can only scale the picture equally in both directions.

10-2-9
Image

To make the dimensions of an image equal to a given value, use the width or height key (the other dimension is then scaled accordingly). If you use both keys simultaneously, you can distort the image to fit a specified rectangle, as shown in the following example:

10-2-10
Image

You can make sure that the aspect ratio of the image itself remains intact by specifying the keepaspectratio key. LaTeX then fits the image as best it can to the rectangle you specify.

10-2-11
Image

Rotations using the angle key add another level of complexity. The reference point for the rotation is the reference point of the original graphic—normally the lower-left corner if the graphic has no depth. By rotating around that point, the height and depth change so that the graphic moves up and down with respect to the baseline, as can be seen in the next examples.

10-2-12
Image

The real fun starts when you specify both a dimension and a rotation angle for an image, since the order in which they are given matters. The graphicx package interprets the keys from left to right. You should pay special attention if you plan to rotate images and want to set them to a certain height. The next examples show the difference between specifying an angle of rotation before and after a scale command. In the first case, the picture is rotated and then the result is scaled. In the second case, the picture is scaled and then rotated.

10-2-13
Image

LaTeX considers the height and the depth of the rotated bounding box separately. The height key refers only to the height; that is, it does not include the depth. In general, the total height of a (rotated) image should fit in a given space, so you should use the totalheight key (see Figure 10.2 on page 632 for a description of the various dimensions defining a LaTeX box). Of course, to obtain special effects you can manipulate rotations and combinations of the height and width parameters at will. Here we show some key combinations and their results.

10-2-14
Image
10-2-15
Image

10.2.4. Setting default key values for the graphicx package

Instead of specifying the same set of key/value pairs over and over again on individual includegraphics commands, you can specify global default values for keys associated with such commands. To do so, you use the setkeys declaration provided by the keyval package, which is automatically included when graphicx is used.

Image

The identifier is an arbitrary string defined by the macro designer. For example, for includegraphics the string Gin was chosen. The key/val-list is a comma-separated list of key/value pairs.

As an example, consider the case where graphicx is used and all figures are to be scaled to the width of the line. Then you would specify the following:

Image

All images included with the includegraphics command will then be automatically scaled to the current line width. (Using linewidth in such a case is usually preferable to using columnwidth, as the former changes its value depending on the surrounding environment, such as quote.)

You can specify defaults in a similar way for any key used with the otatebox command (the other command that has a key/value syntax when graphicx is used). It has the identifier Grot; thus,

Image

specifies that ct should be used for the origin key on all otatebox commands unless locally overwritten.

10.2.5. Declarations guiding the inclusion of images

While key/value pairs can be set only when the graphicx package is used, the declarations described in this section can be used with both the graphics and the graphicx packages.

Where to find image files

By default, LaTeX looks for graphics files in the same directories where it looks for other files. But for larger projects it might be preferable to keep the image files together in a single directory or in a set of directories. A list of directories where LaTeX should search for graphics files can be specified through the command graphicspath, whose argument is a list of directories, each inside a pair of braces {} (even if the list contains only one directory). For example,

Image

causes LaTeX to look in the subdirectories eps and tiff of the current directory.

Defining the file extension search order

The DeclareGraphicsExtensions command lets you specify the behavior of the system when no file extension is given in the argument of the includegraphics command. Its argument {ext-list} is a comma-separated list of file extensions. Full file names are constructed by appending each extension of the list ext-list in turn until a file corresponding to the generated full file name is found.

Because the algorithm tests for the existence of a file to determine which extension to use, when the includegraphics command is specified without an extension, the graphics file must exist at the time LaTeX is run. However, if a file extension is specified, such as includegraphics{gr.eps} instead of includegraphics{gr}, then the graphics file need not exist at the time of the LaTeX run.1 LaTeX needs to know the size of the image, however, so it must be specified in the arguments of the includegraphics command or in a file actually read by LaTeX. (This file can be either the graphics file itself or another file specified with the read key or constructed from the list of file extensions. In the latter case the file must exist at the time LaTeX is run.)

1 For instance, it can be created on the fly with a suitable DeclareGraphicsRule declaration.

With the declaration shown below, the includegraphics command will first look for the file file.ps and, if no such file exists, for the file file.ps.gz:

Image

If you want to make sure that a full file name must always be specified, then you should use the following declaration. In the cases shown below, the size of the (bitmap) image is specified explicitly on the includegraphics command each time.

Image

The action that has to take place when a file with a given extension is encountered is controlled by the following command:

Image

Any number of these declarations is allowed. The meanings of the arguments are described below.

ext The extension of the image file. It can be specified explicitly or, if the argument to includegraphics does not have an extension, can be determined from the list of extensions specified in the argument ext-list of the DeclareGraphicsExtensions command. A star (*) can be used to specify the default behavior for all extensions that are not explicitly declared. For example,

Image

causes all undeclared extensions to be treated as EPS files, and the respective graphics files are read to search for a %%BoundingBox comment.

type The “type” of the file involved. All files of the same type are input with the same internal command (which must be defined in the corresponding driver file). For example, files with an extension of .ps, .eps, or .ps.gz should all be classified as being of type eps.

read-file The extension of the file that should be read to determine the size of the graphics image. It can be identical to ext, but, in the case of compressed or binary images, which cannot be interpreted easily by LaTeX, the size information (the bounding box) is normally put in a separate file. For example, for compressed gzipped PostScript files characterized by the extension .ps.gz, the corresponding readable files could have extension .ps.bb. If the read-file argument is empty (i.e., {}), then the system does not look for an external file to determine the size, and the size must be specified in the arguments of the command includegraphics. If the driver file specifies a procedure for reading size files for type, then that procedure is used; otherwise, the procedure for reading .eps files is used. Therefore, in the absence of any other specific format, you can select the size of a bitmap picture by using the syntax for PostScript images (i.e., with a %%BoundingBox line).

cmd The command to be inserted in the special argument instead of the file name. In general cmd is empty, but for compressed files you might want to uncompress the image file before including it in the file to be printed if the driver supports such an operation. For instance, with the dvips driver, you could use

Image

where the argument #1 denotes the full file name. In this case the final argument causes dvips to use the gunzip command to uncompress the file before inserting it into the PostScript output.

Various possibilities for the arguments of the DeclareGraphicsRule command are shown in Table 10.2.

Image

Table 10.2. Arguments of DeclareGraphicsRule

The system described so far can give some problems if the extension ext does not correspond to the type argument. One could, for instance, have a series of PostScript files called file.1, file.2, .... Neither the graphics nor the graphicx package can automatically detect that these are PostScript files. With the graphicx package, this determination can be handled by using a type=eps key setting on each includegraphics command. To handle this situation more generally, you can define a default type by using a DeclareGraphicsRule declaration for a type * as explained above.

10.2.6. A caveat: Encapsulation is important

We will describe PostScript in more detail in Section 10.4, but it is already important at this point to emphasize that PostScript is a page description language that deals with the appearance of a complete printed page. This makes it difficult for authors to include smaller PostScript pictures created by external tools into their electronic (LaTeX) documents. To solve this problem Adobe has defined the Encapsulated PostScript file format (EPS or EPSF), which complies with the PostScript Document Structuring Conventions Specification [2] and the Encapsulated PostScript File Format Specification [3].

The EPS format defines standard rules for importing PostScript language files into different environments. In particular, so as not to interfere destructively with the PostScript page being built, EPS files should be “well behaved”. For instance, they must not contain certain PostScript operators, such as those manipulating the graphics state, interpreter stack, and global dictionaries.

Most modern graphics applications generate an EPS-compliant file that can be used without difficulty by LaTeX. Sometimes, however, you may be confronted with a bare PostScript file that does not contain the necessary information. For use with LaTeX, a PostScript file does not have to conform strictly to the structuring conventions mentioned previously. If the file is “well behaved” (see above), it is enough that the PostScript file contains the dimensions of the box occupied by the picture. These dimensions are provided to LaTeX via the PostScript comment line %%BoundingBox, as shown below:

Image

The first line indicates that we are dealing with a nonconforming EPS file. Note that the %! characters must occupy the first two columns of the line. The second line, which is the more important one for our purpose, specifies the size of the included picture in PostScript “big” points, of which there are 72 to an inch (see Table A.1 on page 855). Its four parameters are the x and y coordinates of the lower-left corner (LLx and LLy) and the upper-right corner (URx and URy) of the picture. For instance, a full A4 page (210 mm by 297 mm) with zero at the lower-left corner would need the following declaration:

Image

If your picture starts at (100, 200) and is enclosed in a square of 4 inches (288 points), the statement would be

Image

A PostScript display program, such as ghostview, lets you easily determine the bounding box of a picture by moving the cursor on its extremities and reading off the corresponding coordinates. In general, it is good practice to add one or two points to make sure that the complete picture will be included, because of the potential for rounding errors during the computations done in the interpreter.

10.3. Manipulating graphical objects in LaTeX

In addition to the includegraphics command, the graphics and graphicx packages implement a number of graphical manipulation commands.

With the exception of the otatebox command, which also supports a key/value pair syntax in the graphicx package, the syntax for these commands is identical in both packages.

10.3.1. Scaling a LaTeX box

The scalebox command lets you magnify or reduce text or other LaTeX material by a scale factor.

Image

The first of its arguments specifies the factor by which both dimensions of the material are to be scaled. The following example shows how this works.

10-3-1
Image

A supplementary optional argument, if present, specifies a separate vertical scaling factor. It is demonstrated in the following examples, which also show how multiple lines can be scaled by using the standard LaTeX parbox command.

10-3-2
Image
Image

This command is a convenient abbreviation for scalebox{-1}[1]{material}, as seen in the following example:

10-3-3
Image

More interesting special effects can also be obtained. Note in particular the use of the zero-width makebox commands, which hide their contents from LaTeX and thus offer the possibility of fine-tuning the positioning of the typeset material.

10-3-4
Image

10.3.2. Resizing to a given size

It is possible to specify that LaTeX material should be typeset to a fixed horizontal or vertical dimension:

Image

When the aspect ratio of the material should be maintained, then it is enough to specify one of the dimensions, replacing the other dimension with a “!” sign.

10-3-5
Image

When explicit dimensions for both h-dim and v-dim are supplied, then the contents can be distorted. In the following example the baseline is indicated by a horizontal rule drawn with the HR command.

10-3-6
Image

As usual with LaTeX commands involving box dimensions, you can refer to the natural lengths depth, height, otalheight, and width as dimensional parameters:

10-3-7
Image

The unstarred form esizebox bases its calculations on the height of the LaTeX material, while the starred esizebox* command takes into account the total height (the depth plus the height) of the LaTeX box. The next tabular examples, which have a large depth, show the difference.

10-3-8
Image

10.3.3. Rotating a LaTeX box

LaTeX material can be rotated through an angle with the otatebox command. An alternative technique useful with environments is described in Section 10.3.4.

Image

The material argument is typeset inside a LaTeX box and rotated through angle degrees counterclockwise around the reference point.

10-3-9
Image

The rotation algorithm

To understand where the rotated material is placed on the page, we need to look at the algorithm employed. Below we show the individual steps carried out when rotating fbox{text} by 75 degrees. Step 1 shows the unrotated text; the horizontal line at the left marks the baseline. First the material (in this case, fbox{text}) is placed into a box. This box has a reference point around which, by default, the rotation is carried out. This point is shown in step 2 (the original position of the unrotated material is shown as well for reference purposes). Then the algorithm calculates a new bounding box (i.e., the space reserved for the rotated material), as shown in step 3. Next the material is moved horizontally so that the left edges of the new and the old bounding boxes are in the same position (step 4). TeX’s typesetting position is then advanced so that additional material is typeset to the right of the bounding box in its new position, as shown by the line denoting the baseline in step 5. Step 6 shows the final result, again with the baseline on both sides of the rotated material.

Image

For more complex material it is important to keep in mind the location of the reference point of the resulting box. The following example shows how it can be shifted by using the placement parameter of the parbox command.

10-3-10
Image

The extended graphics package graphicx offers more flexibility in specifying the point around which the rotation is to take place by using key/val pairs.

10-3-11
Image

Figure 10.2. A LaTeX box and possible origin reference points

Image

The four possible keys in this case are origin, x, y, and units. The possible values for the origin key are shown in Figure 10.2 (one value each for the horizontal and vertical alignments can be chosen), as are the actual positions of these combinations with respect to the LaTeX box produced from material.

The effect of these possible combinations for the origin key on an actual LaTeX box can be studied below, where two matrices of the results are shown for 90-degree and 45-degree rotated boxes. To better appreciate the effects, the unrotated text is shown against a grey background.

Image

If the specification of the origin is not enough, you also can supply the x and y coordinates (relative to the reference point) for the point around which the rotation is to take place. For this purpose, use the keys x and y and the format x=dim, y=dim. A matrix showing some sample values and their effect on a box rotated by 90 degrees appears below.

Image

The interpretation of the angle argument of otatebox can be controlled by the units keyword, which specifies the number of units counterclockwise in a full circle. The default is 360, so using units=-360 would mean that angles are specified clockwise. Similarly, a setting of units=6.283185 changes the degree specification to radians. Rather than changing the units key on individual otatebox commands, you should probably set up a default interpretation using the setkeys declaration as described in Section 10.2.4.

10.3.4. rotating—Revisited

The material in this section is similar to that of Sebastian Rahtz’s rotating package, which was introduced in Section 6.3.3 on page 296. The functionality of rotating is implemented in this package through the environments turn and rotate; the latter environment generates an object that occupies no space. Using environments has the advantage that the rotated material can contain verb commands. However, the extended syntax of the otatebox command is not supported, so in most cases the latter command is preferable.

10-3-12
Image

10.4. Display languages: PostScript, PDF, and SVG

After typesetting an electronic document, one usually would like to view the generated output “page”—on paper via a printing device, on a PC screen, with a dedicated program or inside a browser, or (why not?) on a portable phone.

Several display languages have been developed over the years. For printing devices PostScript, which is essentially a language for describing a static output page, has become the most important player. In the early 1990s, Adobe developed a light-weight version of PostScript, called the Portable Document Format (PDF) [5]. PDF implements a similar imaging model as PostScript but introduces a more structured format to improve performance for interactive viewing. It also adds links and annotations for navigation.

The increasing affordability of the personal computer has drastically reduced the production cost of electronic documents. The World Wide Web makes distributing these documents worldwide cheap, easy, and fast. The development of the XML family of standards has made it possible to apply a unified approach to handle the huge amount of information stored electronically and to transform it into various customizable presentation forms.

Various techniques are now available to transform LaTeX documents into PDF, HTML (XHTML), or XML so that the information can be made available on the web (several chapters of The Web Companion [56] are dedicated to explaining such techniques). A particularly interesting approach, described below, involves transforming LaTeX-encoded information into a Scalable Vector Graphics (SVG) format.

Thus, LaTeX can continue to play a major role in the integrated worldwide cyberspace. Especially in the area of scientific documents, it will remain an important (intermediate) format for generating high-quality printable PDF or browsable SVG output.

This section gives a short introduction to these three display languages—PostScript, PDF, and SVG. It briefly describes dvips, a dvi-to-PostScript translator, and discusses pspicture, an enhancement of LaTeX’s picture environment using PostScript.

10.4.1. The PostScript language

PostScript [4] is a page description language. It provides a method for expressing the appearance of a printed page, including text, lines, and graphics.

A device- and resolution-independent, general-purpose, programming language, PostScript describes a complete “output page”. The language is stack oriented and uses “reverse Polish” or postfix notation. It includes looping constructs, procedures, and comparison operators, and it supports many data types, including reals, Booleans, arrays, strings, and complex objects such as dictionaries.

PostScript programs are generally written in the form of ASCII source text, which is easy to create, understand, transmit, and manipulate. Because PostScript is resolution and device independent, the same ASCII file can be viewed on a computer display with a previewer, such as ghostscript/ghostview, and printed on a small laser printer or a high-resolution phototypesetter.

The PostScript language lets you mix the following features in any number of combinations:

• Arbitrary shapes can be constructed from lines, arcs, and cubic curves. The shapes may self-intersect and contain disconnected sections and holes.

• The painting primitives permit shapes to be outlined with lines of any thickness, filled with any color, or used as a clipping path to crop any other graphic.

• Text is fully integrated with graphics. In PostScript, text characters are treated as graphical shapes that may be operated on by any of the language’s graphics operators. This is fully true for Type 3 fonts, where character shapes are defined as ordinary PostScript language procedures. In contrast, Adobe’s Type 1 format defines a special smaller language where character shapes are defined by using specially encoded procedures (see below). For complex languages with many thousands of characters (e.g., Chinese and Japanese), composite Type 0 fonts can be used.

• Images (such as photographs or synthetically generated images) can be sampled at any resolution and with a variety of dynamic ranges. PostScript provides facilities to control the rendering of images on the output device.

• Several color models (device based: RGB, HSB, CMYK; standard based: CIE) are available, and conversion from one model to another is possible.

• A general coordinate system facility supports all combinations of linear transformations, including scaling, rotation, reflection, and skewing. These transformations apply uniformly to all page elements, including text, graphical images, and sampled images.

• Dictionaries for color spaces, fonts, forms, images, half-tones, and patterns are available.

• Compression filters, such as JPEG and LZW, are available.

Type 1 and OpenType font outlines

As a complement to the PostScript language, Adobe has defined its Type 1 font format [1]. A Type 1 font program consists of a clear text (ASCII) portion, plus an encoded and encrypted portion. The PostScript language commands used in a Type 1 font program conform to a much stricter syntax than do normal PostScript language programs.

Adobe’s Type 1 model is, like PostScript, fully device and resolution independent. It uses mathematical expressions—in particular, Bézier curves—to define character outlines, thereby guaranteeing flexibility and rendering accuracy. Characters are defined at a size of 1 point in a 1000 by 1000 coordinate system, which can then be scaled, rotated, and skewed at will. Hints can be included to make the representation as exact as possible on a wide variety of devices and pixel densities.

Recently, Adobe and Microsoft jointly developed OpenType,1 a new cross-platform font file format. This extension of the TrueType font outline format can also support Type 1 font data. OpenType adds new typographic features as well.

1 See http://partners.adobe.com/asn/developer/opentype/main.html.

You can move OpenType font files back and forth between platforms (Macintosh and Windows), improving cross-platform portability for any documents that use these types. The bitmap, outline, and metric data are combined into a single, cross-platform OpenType font file, simplifying font management.

OpenType fonts are based on Unicode, an international multi-byte character encoding that covers virtually all of the world’s languages. OpenType thus makes multilingual typography easier by including multiple language character sets in one font. The basic OpenType fonts contain the standard range of Latin characters used in the Western world, as well as several international characters (e.g., the euro symbol). Pro versions add a full range of accented characters to support Central and Eastern European languages, such as Turkish and Polish, and many contain Cyrillic and Greek character extensions in the same font.

Given that OpenType fonts may contain more than 65,000 glyphs, they provide far more typographic capabilities by combining base character sets, expert sets, and extensive additional glyphs into one file. For instance, a single font file may contain many nonstandard glyphs, such as old-style figures, true small capitals, fractions, swashes, superiors, inferiors, titling letters, contextual and stylistic alternates, and a full range of ligatures.

OpenType manages the mapping between characters and glyphs. In particular, its layout features can be used to position or substitute glyphs. For any character, there is a default glyph and positioning behavior. The application of layout features to one or more characters may change the positioning, or substitute a different glyph.

Over the years, thousands of typefaces, including those of the world’s major typesetting companies, such as Linotype, Agfa-Compugraphic, Monotype, Auto-logic, and Varityper, have become available in PostScript Type 1 format. More recently, Adobe has converted the entire Adobe Type Library (thousands of fonts) into OpenType, and other type foundries are following Adobe’s example.

In the TeX world, the (Omega) program (http://omega.cse.unsw.edu.au), an extension of TeX developed by Yannis Haralambous and John Plaice that features multi-byte data structures and is based on Unicode for its internal character representation, can take advantage of OpenType fonts.

10.4.2. The dvips PostScript driver

Tom Rokicki’s dvips program1 is undoubtedly the most widely used dvi-to-PostScript driver. It is a very mature product, with many important and useful features. The special support in dvips is extensive; in particular, it supports the pic commands of the eepic package mentioned in Section 10.1.5.

1 The manual is at http://www.ctan.org/tex-archive/dviware/dvips/dvips_man.pdf. See also [57, Chapter 11] for a detailed description.

The dvips program will automatically generate missing fonts if exists on the system. If a font cannot be generated, a scaled version of the same font at a different size will be used instead (although dvips will complain about the poor aesthetics of the resulting output). Moreover, this facility is configurable and is not limited simply to running .

The output from dvips can be controlled in two ways: by command-line switches for a particular job and by commands in one or more configuration files. Using configuration files, you can set parameters globally for the whole system, on a per-printer basis, and on a per-user basis.

When dvips starts up, a global config.ps file is searched for.2

2 This file must exist on the search path of dvips which is usually something like texmf/dvips/config below the root of the TeX installation tree.

The dvips driver has a plethora of command-line options. Table 10.3 on the following page presents a summary of those options.

Image

Table 10.3. Major options of the dvips program

With the help of the -d option for dvips, you can track down errors and understand what is going on. You must supply an integer specifying the class of information to be displayed. To get several types of information, simply add the numbers together for the types in which you are interested. Choose from the following:

1    specials

2    paths

4    fonts

8    pages

16   headers

32   font compression

64   files

128 memory

For example, calling dvips with the -d 4 option yields information about which fonts are being called and where they are loaded from. An option of -d -1 (all flags are activated) displays a very detailed log of everything dvips does. It will, however, generate an enormous volume of data, so this facility should be used only as a last resort, if a more refined approach fails.

10.4.3. pspicture—An enhanced picture environment for dvips

David Carlisle’s pspicture package reimplements, and extends, LaTeX’s picture environment with the help of PostScript commands that are placed in TeX special commands. It eliminates limitations in standard LaTeX where picture offers only a discrete range of slopes and thicknesses for lines and a limited range of diameters for circles.

There exists a certain amount of overlap between this package and the eepic package, described earlier. Moreover, the pspicture package can be considered as a sort of “stand-in” for the pict2e package that was announced by Leslie Lamport in 1994 in the second edition of the LaTeX book, but which was never written.1

1 For the next LaTeX release a first implementation of the pict2e package (by Hubert Gäßlein and Rolf Niepraschk) is being considered for inclusion in LaTeX.

However, pspicture has the disadvantage that a picture can no longer be viewed with a dvi program that has no facility to interpret and display PostScript commands.1 A “poor man’s” workaround is the companion package texpicture. It uses the standard picture commands as much as possible, but silently omits any picture object that cannot be drawn with standard LaTeX. Of course, the visual result in this case will probably not conform to the finally envisaged version—but at least the document will compile.

1 If you use pdftex to generate PDF directly, you will encounter the same problem. In this case pspicture should not be used.

The dvi file produced with pspicture contains embedded special commands that are set up to be recognized by Rokicki’s dvips driver. Thus, the driver file pspicture.ps, which contains the PostScript code referenced in the special commands for use by the downstream PostScript interpreter, must be present on the TeX installation in the relevant dvips directory, so that it can be found and included by dvips when needed.

Extended or changed commands

The pspicture package extends the functionality of several commands that are available inside LaTeX’s picture environment.

circle extensions

The circle and circle* commands are similar to their counterparts in standard LaTeX but have no limit on their diameters. The thickness of the circle is altered by the linethickness command. The size of the circle produced by circle* is not affected by linethickness.

Image

oval extensions

The oval command acts as described in the LaTeX book, but there is no maximum diameter for the circular arcs, so the oval (in the absence of the optional parameter [part]) always consists of two semicircular arcs joined by a pair of parallel lines. To obtain a “rectangle with rounded corners”, a second optional argument radius was added at the beginning of the oval command. If this option is used, oval works with circular arcs of radius min(radius,x/2,y/2). The following example shows the difference.

10-4-1
Image

line and vector extensions

The vector and line commands are as described in the LaTeX book but no longer have any restrictions on their slopes. The thickness of a sloping line is altered by the linethickness command. The arrowheads drawn by the vector command are of triangular shape, and by default, are larger than LaTeX’s defaults. The size can be controlled with the arrowlength command described below.

The hinlines, hicklines, and linethickness commands alter the thickness of all lines, including slanted lines and circular arcs.

All other commands of LaTeX’s picture environment, such as dashbox, framebox, makebox, multiput, put, and shortstack, are unaltered and act as described in the LaTeX book.

The next example shows how the pspicture package uses PostScript to extend LaTeX’s picture environment. To allow a better understanding of what is going on, we also use the graphpap’s graphpaper command to draw a coordinate grid at a specified position with a given range (first line in the picture environment). Here is what pspicture produces.

10-4-2
Image

To clearly see the effects of the extensions implemented by pspicture, we would like to compare how LaTeX’s standard picture environment would display the above code. However, these commands cannot be run with LaTeX’s picture environment, because we have used unsupported arguments for the vector, circle, and circle* commands. Therefore, we must specify the texpicture package instead of pspicture, as shown below. Thanks to the overlayed coordinate grid, the limitations with respect to the pspicture case are clearly visible. Indeed, the second vector is not rendered correctly, while the diameters of the two circles no longer correspond to what is required.

10-4-3
Image
New commands

The pspicture package also introduces a set of new commands. The Line and Vector commands make it easier to draw a line by allowing you to specify “relative coordinates”.

Image

The above syntax will result in drawing a line (or a vector) between points (x1, y1) and (x1 + x2, y1 + y2).

Image

The Curve command is similar to Line, but generates a line whose curvature is controlled by m (try 1 or -1 first). The value of m does not have to be an integer. Negative numbers curve the line in the opposite way to positive numbers.

Image

The arrowlength command specifies the size of the triangular arrowhead drawn by the vector and Vector commands. Like linethickness, it is an absolute value (i.e., not affected by unitlength), given in any of LaTeX’s units.

Some of the extra features that are not available with the picture environment in standard LaTeX are shown below. The possibilities of arbitrary slopes for the line and vector commands were mentioned previously. The more friendly user interface (allowing for relative coordinates) of the Vector, Line, and Curve commands is appreciated. The first oval command draws a normal ellipse with a thick line (using the hicklines command), while the second oval command draws a rectangle with rounded corners and thin-line borders (using the hinlines command). Finally, we set the line width to 3pt with the linethickness command and show the effect on circles and lines.

10-4-4
Image

10.4.4. The Portable Document Format

Adobe’s Portable Document Format (PDF) [5] is a direct descendant of the PostScript language. Whereas PostScript is a full-blown programming language, PDF is a second-generation, more light-weight graphics language optimized for faster download and display. Most of the advantages of PostScript remain: PDF guarantees page fidelity, down to the smallest glyph or piece of white space, while being portable across different computer platforms. For these reasons, PDF is being used ever more frequently in the professional printing world as a replacement for PostScript. Moreover, all present-day browsers will embed or display PDF material, alongside HTML, using plug-in technology.

The main differences between PostScript and PDF are the following:

• There are no built-in programming language functions: for example, PDF in general cannot calculate values.

• PDF guarantees full page independence by clearly separating resources from page objects.

• PDF files are compact and fully searchable.

• Interactive hyperlinks make PDF files easy to navigate.

• PDF’s security features allow PDF documents to have special access rights and digital signatures applied.

• Font outlines need not be included in the file, because PDF files carry sufficient font information to allow PDF-enabled applications (e.g., Adobe’s Adobe Reader) to mimic the appearance of a font.

• PDF has advanced compression features to keep the size of PDF files small. Moreover, .png and .jpeg images can be inserted directly.

• PDF 1.4 and later versions support a transparent imaging model (PostScript uses an opaque model) and feature multimedia support.

• PDF 1.4 and later versions introduce tagged PDF, a stylized form of PDF that contains information on content and structure. Tagged PDF lets applications extract and reuse page data (text, graphics, images). For instance, tagged PDF allows text to reflow for display on handheld devices, such as Palm OS or Pocket PC systems.

• PDF 1.5, released at the end of 2003, includes features for further optimizing multimedia delivery.

PDF can be viewed and printed on many different computer platforms by downloading and installing the Adobe Reader1 from Adobe. Other PDF viewers exist as well. The best-known free ones are ghostscript,2 which can also produce PDF from PostScript, and Xpdf.3

1 Freely downloadable from http://www.adobe.com/products/acrobat/readermain.html.

2 See http://www.cs.wisc.edu/~ghost/.

3 See http://www.foolabs.com/xpdf/home.html.

Generating PDF directly from TeX

If you have a PostScript file generated from a LaTeX source, you can convert it to PDF by using a “distiller” program. Adobe’s Acrobat Distiller is the best known and most sophisticated of these programs, but ghostscript (and ImageMagick’s convert, which is built on it) also performs well.

To generate PDF directly without going through the dvi-generating step, we have pdfTeX (see below) and MicroPress’s VTeX,1 which has its own direct PDF-generating TeX engine. If you already have a dvi file, you can use Mark Wicks’s dvipdfm dvi driver.2

1 See http://www.micropress-inc.com/.

2 See http://gaspra.kettering.edu/dvipdfm/.

Hán Image Thánh’s pdfTeX is an extension of TeX that creates PDF directly from TeX source files [161]. It also enhances the typesetting capabilities of TeX in some interesting areas [158, 159]. Since 2002 pdfTeX has been part of the standard TeX distributions.

The pdfTeX program lets you include annotations, hyperlinks, and bookmarks in the generated PDF output file. It can work with TrueType fonts and supports the inclusion of pictures in .png and .jpeg formats. The most common technique, the inclusion of Encapsulated PostScript figures, has been replaced by PDF inclusion in this program. EPS files can be converted to PDF by ImageMagick’s convert utility, eps2pdf (both of which call ghostscript internally), Acrobat Distiller, or other PostScript-to-PDF converters.

Navigation is an important aspect of PDF documents. The hyperref package [56, Chapter 2] developed by Sebastian Rahtz and Heiko Oberdiek extends the functionality of the LaTeX cross-referencing commands (including the table of contents, bibliographies, and so on) to produce special commands that a dvi driver or pdfTeX can turn into hypertext links. The hyperref package also provides new commands to allow the user to write ad hoc hypertext links, including those to external documents and URLs.

Because PDF lacks programming language commands, it cannot deal with general raw PostScript commands, such as those used by the pstricks package [57, Chapter 4]. Thus, these commands are not supported.3

3 General PostScript commands can be used with MicroPress’s VTeX, which has a built-in PostScript interpreter.

The standard LaTeX graphics and color packages have a pdftex option, which allow you to use normal color, text rotation, and graphics inclusion commands. The implementation of graphics inclusion makes sure that however often a graphic is used (even if it is used at different scales or transformed in different ways), it is embedded only once.

Producing correct PostScript or PDF

Getting correct PostScript or PDF output from LaTeX systems can sometimes be quite difficult. Michael Shell, in the context of the IEEEtran document class files, but independent of them, has developed the “testflow” diagnostic suite. A test file testflow.tex is first compiled on the user’s system. Next, a PostScript version, testflow.ps, and a PDF version, testflow.pdf, for the output are produced and printed on the output device for comparison to reference files. The input test file is designed to test the various components of LaTeX’s “print work flow”. Its purpose is to provide helpful information to assist users in getting their LaTeX system configured correctly so as to produce good PostScript and PDF output.1

1 Detailed instructions and a detailed explanation available at CTAN: macros/LaTeX/contrib/IEEEtran/testflow/testflow_doc.txt.

10.4.5. Scalable Vector Graphics

Since the mid-1990s, the World Wide Web and the general availability of the personal computer have made the generation, maintenance, and dissemination of electronic documents worldwide cheap, easy, and fast. Moreover, the development of the XML family of standards and the ubiquity of platform-independent scripting languages allow one to save and handle huge amounts of electronically stored information and to transform it into various customizable presentation forms.

For LaTeX documents, a variety of techniques are available to transform them into PDF, XHTML, or XML so that the information can be made available on the web. Thus, LaTeX can continue to play a major role in the integrated worldwide cyberspace, in particular for scientific documents, and especially in areas where fine typesetting is a must.

After a short introduction to Scalable Vector Graphics (SVG), we explain succinctly how LaTeX-encoded information can be encoded into an SVG-format (see [58] for more detail).

SVG for portable graphics on the web

As the web has grown in popularity and complexity, users and content providers have sought ever better, more precise, and more scalable graphical rendering—not just the low-resolution .gif or .png images that are commonly used in today’s web pages. To address this need, the World Wide Web Consortium published the SVG Recommendation, whose current version is 1.1.2

2 Scalable Vector Graphics (SVG) 1.1 Specification, available at http://www.w3.org/TR/SVG11/, was published on January 14, 2003.

SVG is an open-standard vector graphics language for describing two-dimensional graphics using XML syntax. It lets you produce web pages containing high-resolution computer graphics.

As an XML instance, SVG consists of Unicode text. It features the usual vector graphics functions. Its fundamental primitive is the graphics object, whose model contains the following:

• Graphics paths consisting of polylines, Bézier curves, and other elements:

– Simple or compound, closed or open

– (Gradient) filled, (gradient) stroked

– Can be used for clipping

– Can be used for building common geometric shapes

• Patterns and markers

• Templates and symbol libraries

• Transformations:

– Default coordinate system: x is right, y is down,1 the unit is one pixel

1 The reference point of the display area is the upper-left corner. For PostScript, where y runs upward, the reference point of the page is the lower-left corner.

– Viewport maps an area in world coordinates to an area on screen

– Transformations alter the coordinate system (2 × 3 transformation matrix for computers; translate, rotate, scale, skew for humans)

– Can be nested

• Inclusion of bitmap or raster images

• Clipping, filter, and raster effects; alpha masks

• Animations, scripts, and extensions

• Groupings and styles

• SVG fonts (independent from fonts installed on the system)

The W3C SVG web site (http://www.w3.org/Graphics/SVG) is a good first source of information and has a lot of pointers to other sites.

Transforming a LaTeX document into an SVG document

If one has a pure LaTeX source document (i.e., one that includes no EPS files, nor uses any extensions that need TeX special commands), the dvi file can be translated into SVG with Adrian Frischauf’s dvi2svg.2

2 See http://www.activemath.org/~adrianf/dvi2svg/. The dvi2svg program includes SVG font outlines for the characters referenced in the dvi file. SVG font instances were generated for all standard Computer Modern and LaTeX fonts and come with the dvi2svg distribution.

We interacted with the dvi2svg Java library via a small UN*X script called dvi2svg.sh, whose use is as follows:

Image

An example of the use of the dvi2svg program is the translation of two examples in this chapter into SVG. We compile the LaTeX file svgexa.tex and then run dvi2svg.sh on the generated dvi file to obtain the SVG file svgexa1. (If the dvi file contains more than one page several output files are generated.)

Image

Figure 10.3 shows the generated SVG file as viewed with the squiggle program.1 For more complex LaTeX files (in particular, those with EPS or PDF inclusions) you can first generate a PostScript file with dvips, and then use Wolfgang Glunz’s pstoedit program (see [58] for an explanation of how it works).

1 The squiggle SVG browser is part of the Apache Batik distribution (http://xml.apache.org/batik). SVG can also be viewed with Adobe’s browser plugin svgview (http://www.adobe.com/svg).

Image

Figure 10.3. SVG generated from a dvi file

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.118.93.175