Up: Strategies for using scripts

Basic PostScript

One of the easiest ways to create graphics via CGI scripts is to write out PostScript files, and convert them to gif files. One advantage of this strategy is that one can use a program like xfig to interactively create a large part of a picture interactively. At run time, the script fills in the remainder.

PostScript is a very powerful graphics language. It is possible to create sophisticated graphics. However, for most applications, a small handful of commands and concepts suffice.

For more information, consult

PostScript Language Tutorial and Cookbook, Adobe Systems, Addison-Wesley

Drawing

To draw in PostScript, one creates a path which is then either stroked or filled. The following example creates two squares, the first outlined, the second solid.
newpath
20 20 moveto
20 40 lineto
40 40 lineto
40 20 lineto
closepath
stroke

newpath
60 60 moveto
60 80 lineto
80 80 lineto
80 60 lineto
closepath
fill
You can change the line width and current color:
2 setlinewidth
.5 .5 0 setrgbcolor

Coordinates

By default, the PostScript coordinate system starts in the lower left corner of the page, and has units of 1/72 inch. It is frequently convenient to translate and scale the axes.

Two other useful commands in this context are gsave and grestore. They save and restore the graphics state, including color, line width, current path, coordinate transformations and so on.

gsave
72 72 scale           %scale by a factor of 72 in x and y
1 1 translate         %translate one inch
.25 setlinewidth      %quarter inch lines

%draw a line
0 0 moveto 1 1 lineto stroke
grestore

%draw a line in the original coordinate system
200 200 moveto 300 300 lineto stroke

Fonts

Unsurprising, PostScript has sophisticated font processing abilities. A simple example is given below:
/Helvetica findfont            %load the font dictionary
14 scalefont                   %scale to 14pt
setfont                        %make this the current font
30 30 moveto
(Julius Caeser) show           %display text
You must always go through the first three steps to retrieve a font. In PostScript, strings are denoted with parentheses.

Variables

In order to read PostScript written by applications like xfig, you need to be familiar with PostScript variables. Moreover, even in simple applications, it is convenient to use the computational power of PostScript.

PostScript maintains a sort of macro dictionary. The macros can expand to data or procedures or other data types. Literal names are denoted by the '/' character in PostScript.

To define a variable or a procedure, use this syntax:

/topmargin 720 def         %define constants
/leftmargin 72 def

/inch { 72 mul } def       %define a procedure

newpath
leftmargin topmargin moveto
3 inch 4 inch lineto
stroke


Up: Strategies for using scripts

[HOME] The Geometry Center Home Page

Comments to: webmaster@geom.umn.edu
Created: May 09 1996 --- Last modified: Tue Jun 4 22:13:36 1996