The PostScript Language

ArticleCategory: [Choose a category, translators: do not translate this, see list below for available categories]

SoftwareDevelopment

AuthorImage:[Here we need a little image from you]

[Photo of the Author]

TranslationInfo:[Author + translation history. mailto: or http://homepage]

original in en Emre Demiralp

AboutTheAuthor:[A small biography about the author]

Abstract:[Here you write a little summary]

This is the first of a series of articles about PostScript.

Stock the chaff, the day will come to use it.
-Turkish Proverb-.

ArticleIllustration:[One image that will end up at the top of the article]

[Illustration]

ArticleBody:[The main part of the article]

Introduction

The main purpose here is not to teach each detail of this software but to give sufficient material for the persons who find PostScript an interesting and enjoyable programming language for document preparation. Although we do not intend to write a technical paper or a textbook or a bible on this topic we are going to try to present necessary and sufficient information for PostScript.

The main ideas behind PostScript were created twenty two years ago by John Gaffney at the Evans & Sutherland Computer Corporation. It was known as the "Design System" at the beginning but later it was developed under the name PostScript by Adobe Systems Incorporated as a platform and device independent tool for page designing. Adobe Systems Incorporated was formed by Chuck Geschke and John Warnock in 1982. C. Geschke and J. Warnock undertook a new design and implementation of the language, to which Doug Brotz, Billi Paxton, and Ed Taft made major contributions. Nowadays it is one of the major document preparation tools although it is not directly used by most end users. Its capabilities are at quite high levels however many lazy users who do not want to get into the details of this powerful language prefer to use the other end-user-oriented tools which are mainly based on the "What You See Is What You Get" philosophy. To tell the truth, many WYSIWYG tools use PostScript file formats for maintaining the documentation products or for using as an interface for other jobs like printing. In these senses, it still survives as our old friend which serves as a powerful assistance to many computer jobs related to drawing, coloring, image processing, color separation, simulation and animation even if it may not explicitly show up itself in the procedures. On the other hand, if you desire to learn its structure for programming you will find it not so difficult.

The PostScript commands are executed through certain interpreters. Amongst these, a well-known software is freely available on the public domain of Internet. This is named "ghostscript" by Aladdin Enterprise. There is also a useful graphical interface, "ghostview", released by the same organization. GNU project has also its own versions for ghostscript. These are available in every Linux platform and all main Linux distributions contain them in standard installations. Here we deal with ghostscript and its certain specific structures and properties although the sample programs can be executed through other interpreters. Assume that we activate the X Window server and open an xterm window. If we want to use ghostscript then each command or command groups will be given at the command prompt which will be appeared after issuing the command

Initializing... done. Ghostscript 2.6.2 (4/19/95) Copyright (C) 1990-1995 Aladdin Enterprises, Menlo Park, CA. All rights reserved. Ghostscript comes with NO WARRANTY: see the file COPYING for details.
GS>_


A specific blank window will be opened at the same time with the appearence of this command prompt. If we want to dismiss the ghostscript session, all we have to do is to issue quit command at GS> prompt. EOF (Ctrl-D) works also for the same purpose.

Ghostscript can execute the commands by getting them from a file also. In this case we open a file named, for example, sample.ps . All commands to be executed by ghostscript are written in this file. Hence we can call the content of this file a PostScript program. The entire content of this program or its individual commands will be consecutively executed by ghostscript if we issue the following command at the shell prompt of the xterm window of linux

gs sample.ps

and the display (if the program aims at the creation of a display, of course. In fact, PostScript can be used for other purposes like mathematical calculations, stack operation etc. We will mention them in future articles of this series) will be appearing on the ghostscript window. If the program produces more pages than a single one then the ghostscript window shows the first page and a showpage prompt appears at the ghostscript commandline requesting enter key pressing for the next page.

PostScript uses Reverse Polish Notation (RPN - like HP pocket calculators). In other words parameters for a command are given before the command. The commands are separated by blank spaces. It uses stack operations for data processing and command execution. There are four available stacks in PostScript usage: the operand, dictionary, execution and graphics state stacks. The operand stack holds arbitrary PostScript objects that are the operands and results of PostScript operators being executed. We can give some examples from arithmetical operations. For instance,

20 30 add 10 sub 

produces 40 since 20 30 add creates 50 and sub produces 40 by using 50 together with 10. mul (multiplication) and div (division) work in the same way. The name '=' is associatedwith a procedure that pops one object from the operand stack and writes a text representation of its value to the standard ouput file, followed by a newline. == has a similar action but it writes syntactic representation of its operand to the standard output file. pop command removes the top element from the operand stack and discards it. We will mention about the stacks in a more detailed manner later articles of this series.

How do we use PostScript for drawing figures?

We can start drawing figures through PostScript by considering the geometrical structure of the page to be designed. The locations of the points on a page are denoted via pixel units which are one seventy second of an inch in PostScript language. The left bottom side of the rectangular page is assumed to be the location which has the (0,0) coordinates and the horizontal and the vertical sizes of the page are defined as 612 and 792 respectively. These sizes are for the letter type of papers. There are other possibilities for the definition of the paper sizes like

note for 540 and 720 or
legal for 612 and 1008 or
a4 for 595 and 842 .

These are regular gs commands. The command 'a4' will resize your drawing sheet to the appropriate size.

The paper size definition can be found in the initialization file whose name is gs_statd.ps. It can be found in /usr/lib/ghostscript for Slackware. You can define any non-standard paper size by making convenient additions and modifications on this file as we will mention later in this series of articles. Here we assume that we use the default paper type letter in this presentation.

The second step after taking the paper in desired sizes in drawing a figure is to locate the curser at the beginning of the drawing. This can be accomplished by issuing the command

x y moveto

where x and y denote respectively the horizontal and vertical coordinates of the point where the cursor will be located. x and y are pure numbers and considered in pixel units. As you can see the functional structure of the PostScript is a little bit different from the other programming languages like C, Fortran. moveto is the command which takes the action, in other words it moves the cursor to somewhere whose location is given by x and y. Since PostScript uses a stack the parameters are given consecutively to the stack first. Then the command is given. When it enters the stack it accepts the previous two items as its parameters. The syntax here is different for the end user who is familiar with languages like C, Fortran. For this reason we have emphasized on this topic here. As a conclusion we can say that each command which needs some parameters must be given after its parameters.

Now we are ready to start to draw the figure. Let us start with a rather simple figure, just a straight line segment. To draw this, all we have to do is to issue the following command

xx yy lineto

where xx and yy denote the location of the endpoint of the line segment. Its beginning point is the present location of the cursor, x and y . Hence, this command constructs a straight line segment from x y to xx yy . The actual drawing necessitates the path definition newpath and stroke command. Now let us write a PostScript program to draw a rectangle. This can be done by using the information given above. The program which is assumed saved in the file sample1.ps can be given as follows

newpath
100 100 moveto
300 100 lineto
300 250 lineto
100 250 lineto
100 100 lineto stroke

Although we have given each command in separate lines, this is not really necessary. We could give them in the same line by inserting a blank space between consecutive commands as we mention before.

PostScript has commenting facility like the other programming languages. Whole material which follows a percentage sign in a line is interpreted as comment by the interpreter.

newpath
% Cursor initialization
100 100 moveto
% Drawing the rectangle
300 100 lineto
300 250 lineto
100 250 lineto
100 100 lineto stroke

If we now issue gs sample1.ps command at the prompt of the xterm window then the usual ghostscript window appears containing the desired display of the rectangle. We do not need to invoke gs interpreter at every time of displaying. In fact,
(sample1.ps) run
command does the same thing through the GS> prompt.

The stroke command tells to the interpreter to draw the figure. For the above program the ghostscript window displays the rectangle with edges of 200 and 150 points in horizontal and vertical directions.

The straight lines do not need to be vertical or horizontal. They can be constructed in any direction.

As you will see when we display the result through ghostscript, this program creates a triangle. You can create any kind of figures which are composed of broken lines or line segments by using moveto and linetocommands.

There are two more commands to be used in the above figure constructions. These are rmoveto and rlineto . They need two parameters and can be used as follows

x y rmoveto
x y rlineto

where x and y are the horizontal and vertical distances between the initial and final points of each action. 'r' in rmove and rlineto stands for 'relative'. In other words the first command moves the cursor x units horizontally to right and y units to up from its present location. The second command behaves similarly but it draws a line and moves the cursor to the final point instead of only moving cursor. These are referring commands and the parameters are given by taking the initial location as the reference point.

All above examples use a default linewidth for the drawing. This value is 1 pixel. However user can define the line width of the drawing at anywhere in the program. This can be done by issuing the command

x setlinewidth

where x denotes the line width in pixels. The effect of this command continues until the next line width setting in the program. There is no limitation for the number of line width settings in a program.

Of course, the drawing in PostScript is not limited to straight lines. The circular arcs can be also produced. For this purpose we can use the following command

x y r a b arc

where x, y, r, a and b stand for the horizontal and vertical coordinates of the center of the circular arc, the radius of the arc, the angle between the positive part of the horizontal axis and the central rays which pass through the beginning and the final points of the arc. The angles are measured counterclockwise. If the beginning point of the arc is not the present location of the cursor, then a straight line between the currentpoint (the location of the cursor) and the beginning point arc is also added to the figure. To understand the situations you can have a look at the display of the following PostScript program.


3 setlinewidth
200 200 moveto
100 200 100 0 75 arc
stroke
300 300 moveto
400 500 200 20 50 arc
stroke

Therefore we must be careful to place the cursor at the beginning point of the arc if do not want the extra line mentioned above. However there is another way to get rid of this effect. In fact, the currentpoint can be made empty valued. In other words at the beginning of the path it has no parameter values. There is no assignment for the location of the cursor. Once the drawing is started the final point of the path becomes the current point. If we issue newpath command then PostScript erases the assignment for the cursor point and treats as if the drawing will start just from that instance. Therefore the above program can be modified by replacing the fifth line with a line which contains only newpath command. If this is done and displayed then the same output, except the extra line segment, of the above program will be obtained.

A path is begun by executing the newpath operator. This initializes the current path to be empty. The path is then built up via execution of some commands for adding segments to the current path.

arc command can be used to draw a full circle. It is sufficient to give the beginning and the final angles of the arc as 0 and 360 respectively. If this is done under a newpath a complete circle is obtained. arc command can be used to produce ellipses also. This can be accomplished by using scaling property of PostScript. The user can rescale of the horizontal and vertical units separately via the following command.

x y scale

where x and y denote respectively the horizontal and vertical scaling factors. This means that the case where these factors are equal to 1 creates no effect on the drawing. The effect of the scaling is maintained until the next scaling command is issued. The next issued scaling command does not remove the effect of the previous one but it combines its own effect with the previous one. If we assume that the previous scaling command parameter has the scaling factors x1, y1 while the next scaling command parameter has x2, y2 factors then the combined effect of these commands has the scaling factors x1*x2, y1*y2 . This point must not be kept far from the eyes to avoid undesired results in the displays, such that some paths may slide out of the paper surface. PostScript assumes the nonexistence of scaling by default. The following PostScript program which is assumed to be saved in the file sample4.ps forms an example to explain the scaling.

3 setlinewidth
200 200 100 0 360 arc
stroke
newpath
2 1 scale
200 300 50 0 360 arc
stroke
newpath
1 4 scale
100 150 40 0 360 arc
stroke

As can be noticed, the scaling affects each size including the line width. The line widths of the ellipses and the circle created by the above program are different due to this reason.

PostScript also has two other commands for arc drawing. One of them, arcn , is mainly same with arc except the drawing direction. arcn draws arc clockwise. The third arc drawing command draws a circular arc which is tangent to two given lines at the endpoints. It can be issued as follows.

x1 y1 x2 y2 r arcto xt1 yt1 xt2 yt2

where xt1, yt1, xt2, yt2 denote the horizontal and the vertical coordinates of the arc while the end points of the tangent lines have the the values x0, y0, x1, y1 and x1, y1, x2, y2 respectively and r stands for the radius of the arc. If the path is not new or the current point does not coincide with the beginning of the arc then a line joining the current point and the beginning point of the arc is added to the path. At the end of the drawing the currentpoint becomes xt2, yt2 .

PostScript has also a Bezier algorithm based command which can be effectively used in the interpolation or extrapolation of a given data for plotting. This command is curveto and can be used to form the plots based on the interpolation or extrapolation of a given set of data. The command can be used as follows.

x1 y1 x2 y2 x3 y3 curveto

where the curve starts at the current point whose coordinates are assumed to be x0, y0 . It is tangent to the line between the points x0, y0 and x1, y1 at the beginning point. The curve ends at the point x3, y3 and is tangent to the line between x2, y2 and x3, y3 . By default all these four points are assumed to be different and they determine the shape of the figure.

Writing facilities in PostScript

PostScript has various fonts which are used as standard fonts for desk-top publishing. It has also font creating facilities which can be accessed by defining dictionary stacks where fonts are available. The following PostScript program can be given as an example.

/Times-Roman findfont
15 scalefont
setfont
100 500 moveto
(I love PostScript!) show
/Times-Italic findfont
20 scalefont
setfont
100 450 moveto
(I love PostScript!) show
/Times-Bold findfont
25 scalefont
setfont
100 400 moveto
(I love PostScript!) show
/Helvetica findfont
30 scalefont
setfont
100 350 moveto
(I love PostScript!) show
/Courier findfont
35 scalefont
setfont
100 300 moveto
(I love PostScript!) show
/Helvetica-Bold findfont
40 scalefont
setfont
100 250 moveto
(I love PostScript!) show
showpage

As can be extracted from the program findfont command is used for getting an access to the desired font structure. The name of the font starts with / and is given to the command as a preceding parameter (where / tells the interpreter to push this value on the stack 'as is'. When we get into the details of stack operations later this point will be more clear. After the selection of the command the scaling is defined through the scalefont command. The scaling factor is given as a preceding number to this command. After scaling of the font, the command setfont makes the font ready for future usage in the program. After we locate the cursor through the moveto command with appropriate parameters, the text material encompassed by the parenthesis is given a parameter for the show command. The showpage command finalizes the displaying of the written material. The above program uses different fonts in type and size for the same text located at different positions. The number of the avaliable fonts for PostScript can be found by searching the locations of the fonts in the tree structure of the linux system you use. The text can be adjusted through lines, curves and by some other tool. So any kind of writing, in principle, is possible. It is just a matter of design.

Painting and color usage in PostScript

PostScript language is equipped with several facilities to paint figures or create colorful pictures. Let us start by mentioning the coloring commands first. PostScript uses black as the default color unless a color specification command is issued. Hence the output of the all previous programs were black and white pictures. To use color in the output PostScript can use three different coloring command. The first one is based on the rgb color format. In this format each color is assumed to be composed of three main colors: red, green and blue. The color components can be given by individual intensity parameters which can take the values between 0 and 256. The intensity parameters can accept the decimal fractional values up to three digit precision like 111.223. Therefore the command expected by PostScript must be given as follows.

x y z setrgbcolor

where x,y,z are the intensity parameters for the red, green and blue components and setrgbcolor is the command. In this convention 1 0 0 setrgbcolor creates red color while 0 1 0 setrgbcolor creating green. Black corresponds to the case where all intensity parameters take the value of 1. Color setting command continues to affect every drawing and painting until the next color setting command is issued. When this happens the effect of the first setting is completely removed and the new setting dominates everything. The number of usage for the color setting is unlimited. By approriately using the color settings you can create your pictures just as you want. It is a matter of art and up to you.

The second color setting facility is based on a four component color format. This is called cmyk color format. The four basic color components are cyan, magenta, yellow and black respectively. Each color component contributes the final color according to an intensity parameter which can vary between 0 and 1. The corresponding PostScript command is therefore as follows

w x y z setcmykcolor

where w, x, y, z are the intensity parameters for the color components cyan, magenta, yellow and black respectively. The fractional decimal values can also be used for intensity parameters. This command also continues its effect on everything until the next command is issued. When this is done the new setting overdominates the preceding setting. There is no limitation on the number of usage for this command in a program.

Third command can be used as follows

x y z sethsbcolor

where x, y, z stand for the intensity paremeters of three different properties of the color. First one corresponds to hue which determines the location of the color in the spectrum of the light. The second one, saturation and the third one, brightness corresponds to the saturation and the brightness of the color. This format is preferred when the location of the color in the spectrum via a loop or the brightness and/or saturation become the properties to be controlled. The reader who is not familiar to hsbcolor he/she can check the use of the xfig facility under linux.

The most important PostScript command for painting is fill and closepath . The following example program which is assumed to be saved in the file sample6.ps clarifies important aspects of the painting and coloring through PostScript.

1 1 0 0 setcmykcolor
100 100 moveto
300 100 lineto
300 250 lineto
100 250 lineto
100 100 lineto
stroke
1 0.5 0.8 0 setcmykcolor
5 setlinewidth
200 200 moveto
400 300 lineto
300 300 lineto
closepath fill
stroke
1 0 0 setrgbcolor
3 setlinewidth
200 200 moveto
100 200 100 0 75 arc
stroke
newpath
400 500 200 20 50 arc
stroke
0 0 1 0.2 setcmykcolor
3 setlinewidth
200 200 100 0 360 arc
stroke
1 0 0 setrgbcolor
newpath
2 1 scale
200 300 50 0 360 arc
gsave fill grestore stroke

stroke
0 1 0 setrgbcolor
newpath
1 4 scale
100 150 40 0 360 arc
gsave fill grestore stroke

where closepath command closes an open path by joining two end points by a straight line while fill serves to fill inside of the closed path with the current color.

PostScript can also create grey tones. This can be done through the command

x setgray

where x is the intensity of the graycolor and its value can change from 0, which corresponds to black, to 1 which corresponds to white. The following program which is saved under the name sample7.ps is constructed in a sufficiently self=explanatory manner.

0.2 setgray
10 setlinewidth
100 700 moveto
200 0 rlineto
stroke
newpath
0.3 setgray
100 600 moveto
200 0 rlineto
stroke
newpath
0.4 setgray
100 500 moveto
200 0 rlineto
stroke
newpath
0.5 setgray
100 400 moveto
200 0 rlineto
stroke
newpath
0.6 setgray
100 300 moveto
200 0 rlineto
stroke
newpath
0.7 setgray
100 200 moveto
200 0 rlineto
stroke
newpath
0.8 setgray
100 100 moveto
200 0 rlineto
stroke

Before the completion of this presentation we can recommend to write more complicated and comprehensive programs for the users who find PostScript as an enthusisastic tool. In the next articles of these series more details about the PostScript language. All questions and recommendations are welcome for our presentations. We shall give sufficient credit to these in our coming articles.

The author thanks to Oliver Thilmann for his very helpful comments for the organization and presentation of this article.



For more information: