TweetFollow Us on Twitter

The Perils Of PostScript

The Perils Of PostScript


Letting your application rather than the LaserWriter driver convert QuickDraw commands into PostScript is simple in most cases, yet when you use direct PostScript to print documents, subtle interactions between the QuickDraw and PostScript imaging models can cause problems. This article will help you in two important areas: using a font from PostScript while selecting it using QuickDraw and preserving your PostScript state while using QuickDraw to select fonts.

When selecting a PostScript font from QuickDraw, an application first calls GetFNum (see Inside Macintosh, volume I, page 223 [IM I-223]) to get the Font Family ID for a particular font. It then calls TextFont (IM I-171) to actually select it. The name passed to GetFNum is the name of the font as seen in the Font menu (for example, Helvetica).

In PostScript, fonts are selected by name using the findfont (see PostScript Language Reference Manual, page 156 [PLRM 156]) and setfont (PLRM 215) operators. If the application attempts to select a font named Helvetica®, however, it will find that this font doesn't exist. This is because the LaserWriter performs a special operation on the font called encoding. Font encoding is the process of mapping missing characters into another font.

For example, a character like ø may not exist in the standard Helvetica font. In order to provide that character, the LaserWriter driver will modify the Helvetica font, inserting a reference to the ø character in the Symbol font. Once this is done, the font is no longer standard Helvetica, so it is renamed. The actual name is something like |_____Helvetica, but this naming convention is not standard and could change in the future.

So if you don't know the font's name, how can you select it? Simple, let QuickDraw do it. When you select a font via TextFont and then use it via one of the QuickDraw text drawing routines (such as DrawChar or DrawString [IM I- 172]), the LaserWriter driver handles the complex task of selecting an appropriate font on the PostScript device. This includes downloading and encoding the font if necessary. Using QuickDraw to select the font not only saves you a lot of work, but also improves compatibility. The process of font downloading and character encoding could change in the future, and if your application does it internally, it will have to be revised. If you use QuickDraw to download the font, your application will be immune to changes in the font downloading mechanism.


Now let's look at the code to actually select a font. The following procedure will select a font for any device, QuickDraw or PostScript:
PROCEDURE  SetFont;(fontName: Str255; fontSize: INTEGER;
    fontStyle: Style);
    theFontID:  INTEGER;
    thePenLoc:  Point;
    GetFNum(fontName, theFontID);   (* Get the font ID. *)
    TextFont(theFontID);    (* Set it *)
    TextSize(fontSize); (* Set the size *)
    TextFace(fontStyle);    (* ...and the style. *)
    GetPen(thePenLoc);  (* Save the current pen position. *)
    DrawChar(' ');  (* Draw a space so the font gets downloaded.*)
    MoveTo(thePenLoc.h, thePenLoc.v);   (* Restore original pen *)
                (* position. *)

There are two important things to note in the SetFont procedure above. First, the procedure uses the GetFNum trap to get the Font ID. This is essential to make sure that you get the correct font. (See Technical Note #191, Font Names for more information.) Second, the SetFont procedure calls DrawChar to draw a space. This is required to force the font selection on PostScript devices, since the TextFont call only changes the txFont field of the GrafPort. By actually using the font (via DrawChar) the LaserWriter driver's StdText GrafProc is called, and selects the font on the printer. Subsequent calls to the PostScript show (PLRM 222) operator will use this font. Since DrawChar will change the pen position, it is saved (via GetPen [IM I-169]) and restored (via MoveTo [IM I-170]).


Now that we have a font selected, we need to actually draw something with it. For now, as an example, let's say that we want to draw some text with the show operator. We'll send our PostScript using the following procedure. Although convenient for sending PostScript in our example, this method is very inefficient and should not be used in an application. Here's the code:
PROCEDURE SendPostScript(theComment: Str255);
        PSCommand   : Str255;
        CommandHdl  : Handle;
        CRString    : Str255;
        theError    : OSErr;
        CRString := ' ';
        CRString[1] := CHR(13);
        PSCommand := theComment;
        PSCommand := CONCAT(PSCommand, CRString);
        theError := PtrToHand(POINTER(ORD(@PSCommand) + 1),
        if theError <> noErr THEN BEGIN
            (* Handle the error! *)
            LENGTH(PSCommand), CommandHdl);

The procedure simply takes a string of text, adds a carriage return at the end of it, and converts it into a handle. The handle is then passed to the PostScriptHandle picture comment, which actually sends it to the printer. Since this procedure created the handle, the procedure also disposes of it. Again, this is not how a normal application would do it, but it keeps things nice and localized for this example. So now that we can send PostScript, consider the following:

SetFont('Helvetica', 14, [bold]);
PicComment(PostScriptBegin, 0, NIL);        
        (*** QuickDraw representation of graphic. ***)
    (* These calls are only executed by QuickDraw *)
    (* (i.e. non-PostScript) devices.   *)
        MoveTo(50, 50);
        DrawString('This is some gray text.');
        MoveTo(100, 100);
        LineTo(300, 300);
        (*** PostScript representation of graphic. ***)
    (* These calls will only be executed by PostScript devices.*)
    SendPostScript('50 50 moveto (This is some gray text.) show');
    SendPostScript('.10 setgray');
    SendPostScript('100 100 moveto 300 300 lineto stroke');
PicComment(PostScriptEnd, 0, NIL);

In this fragment, the call to SetFont sets the PostScript currentfont to be Helvetica. The PostScriptBegin comment is used to suppress QuickDraw calls on PostScript devices, and vice versa. When the LaserWriter sees PostScriptBegin, it ignores all QuickDraw drawing calls, and just executes picture comments. When a PostScriptEnd is received, the LaserWriter will once again interpret QuickDraw calls. The LaserWriter driver will ignore the QuickDraw representation, and begin executing the SendPostScript calls. The first one draws a string of text, the second one changes the default gray level of the printer from 100% black to 10% black using the setgray (PLRM 216) operator, and the third one draws a diagonal line using the new gray level. Note that the QuickDraw representation for a gray level is handled by using PenPat (IM I-170).


The fragment we just looked at illustrates a good method for sending both QuickDraw and PostScript. It also demonstrates a new problem. When the PostScriptBegin comment is sent, the LaserWriter driver performs a PostScript gsave (PLRM 166) operation. This saves the current graphics state required for QuickDraw printing. The application can then do what it needs to the state without having to worry about side effects on the QuickDraw environment. When the LaserWriter driver receives a PostScriptEnd comment, it performs a grestore (PLRM 165) operation to restore the QuickDraw state. Normally this is exactly what you would want. But there are cases when an application may want to execute some QuickDraw commands without losing the PostScript state is has setup.

For example, the above code fragment set the gray level of the printer to 10%. At the time we did the PostScriptEnd comment, the gray level was restored to 100%. If we then want to change the font size, and redraw the text, we would have to resend the setgray operator. It would look like this:

   (* Change the font size.*)
    SetFont('Helvetica', 24, [bold]);
    PicComment(PostScriptBegin, 0, NIL);        
        (*** QuickDraw representation of graphic. ***)
        (* These calls are only executed by QuickDraw *)
        (* (i.e. non-PostScript) devices.*)
        (* The QuickDraw state is unaffected, so there's *)
        (* no need to call PenPat again. *)
        MoveTo(250, 50);
        LineTo(750, 50);

        (*** PostScript representation of graphic. ***)
        (* These calls only executed by PostScript devices. *)
        (* Since the PostScript state was cleared, we need *)
        (* to resend the setgray operator. *)
        SendPostScript('.10 setgray');
        SendPostScript('250 50 moveto 750 50 lineto');
    PicComment(PostScriptEnd, 0, NIL);

Although resending the setgray operator isn't difficult, an application may have set a lot more attributes. To avoid the overhead of resending this state, a new comment may be used. This comment is #196--PostScriptBeginNoSave.

When PostScriptBeginNoSave is used with PostScriptEnd, the gsave and grestore operations are not performed. This means that the application is completely responsible for the graphics state of the printer. If you are doing all of your imaging via PostScript this is not a problem. If you plan on mixing PostScript and QuickDraw, you must be very careful. Changes to attributes like line width and the transformation matrix will have a significant effect on QuickDraw drawing operations. If the comment is used for the above example, the code will look like this:

   (* Now illustrate the use of the PostScriptBeginNoSave  *)
    (* PicComment. *)
    PicComment(PostScriptBeginNoSave, 0, NIL);
        SendPostScript('.10 setgray');
    PicComment(PostScriptEnd, 0, NIL);
    (* At this point, the gray level of the device is 10% black *)
    (* Now draw something using this state. *)
    (* Draw a light gray line using QuickDraw. *)
    MoveTo(50, 400);
    Line(100, 100);
    (* At this point, the gray level is still 10%, so we must *)
    (* reset it  to black. *)
    PicComment(PostScriptBeginNoSave, 0, NIL);
        PenPat(black);  (* Reset QuickDraw gray level.  *)
        SendPostScript('1.0 setgray');  (* Reset PostScript gray*)
                                (* level.   *)
    PicComment(PostScriptEnd, 0, NIL);

Note that instead of sending PostScriptBegin as the first operation, we now send PostScriptBeginNoSave. We then change the gray level to light gray in the QuickDraw world, and 10% black for PostScript. Since we used PostScriptBeginNoSave, sending PostScriptEnd does not effect the state of the printer (i.e. the gray level remains at 10%). Now we want to draw something with the new state. We first send the PostScriptBegin comment, which saves the state we set up, as well as disabling the QuickDraw calls on PostScript devices.

We then send a QuickDraw representation of the line, followed by PostScriptEnd. On QuickDraw devices, the line will be drawn using the ltGray pen pattern. On PostScript devices, the line will be drawn using 10% black. After the line has been drawn, we need to reset the state of the device for subsequent drawing operations. This is done by once again sending the PostScriptBeginNoSave comment, followed by the commands to reset the gray level, as well as any other attributes of the printer.

In summary, we have looked at two ways of avoiding the perils of PostScript. The first was how to use a font from PostScript while choosing it using QuickDraw. The supported method for this was demonstrated by the SetFont procedure. The second was how to preserve your PostScript state while still using QuickDraw to select fonts.

Scott "Zz" Zimmerman is a DTS printing guru. (He's particularly impressed with the strictly enforced dress code at Apple.) In his spare time he sails, scuba dives for lobsters, and plays the piano, guitar, and saxophone. His doorway is adorned by a melted gummy rat, a good luck charm from his Intel days. At home, atop his monitor is perched a rare Asian black scorpion (behind glass, we hope). His other cuddly pets include two geckos and an iguana. *


Community Search:
MacTech Search:

Software Updates via MacUpdate

Gordon Ramsay DASH: Guide to upgrading a...
If we've learned anything about celebrity chef Gordon Ramsay over the years, it's that you don't want him angry and breathing down your neck. He's not above calling you out on TV, making a mockery of your efforts in the kitchen in front of... | Read more »
Galaxy of Trian (Games)
Galaxy of Trian 1.1.0 Device: iOS Universal Category: Games Price: $6.99, Version: 1.1.0 (iTunes) Description: Galaxy of Trian is an exciting, fast paced digital board game based on the highly acclaimed tabletop title. | Read more »
Dead In Bermuda (Games)
Dead In Bermuda 1.0 Device: iOS Universal Category: Games Price: $4.99, Version: 1.0 (iTunes) Description: | Read more »
The Little Fox (Games)
The Little Fox 1.0.1 Device: iOS Universal Category: Games Price: $2.99, Version: 1.0.1 (iTunes) Description: The Little Fox is an alternative perspective on the world-renowned ‘fairy tale for adults', The Little Prince by Antoine de... | Read more »
5 popular free fertility apps
There was a good article this week in The Independent about how more women are using fertility appsas a de facto form of contraception. It's apparently not working too well, leading to numerous unwanted pregnancies. [Read more] | Read more »
How to get more cars in CSR Racing 2
NaturalMotion and Zynga brought a lot of real life cars to the table for CSR Racing 2. From souped up everyday rides made by Nissan and Hyundai to supercars produced by the likes of McLaren and Pagani, there really is something for everyone. [... | Read more »
Crypt of the NecroDancer Pocket Edition...
Crypt of the NecroDancer Pocket Edition 1.0 Device: iOS Universal Category: Games Price: $4.99, Version: 1.0 (iTunes) Description: Crypt of the NecroDancer is an award winning hardcore roguelike rhythm game. Move to the music and... | Read more »
Gear-grinding puzzle title Inner Circle...
If you saw our post earlier this month announcing the imminent release of ZPlay’s new creation, Inner Circle, you’ll be happy to know that it’s now available on the App Store. Established in 2010, developer and publisher ZPlay have taken the... | Read more »
CSR Racing 2: Your guide to what's...
CSR Racing 2, or CSR2, as it likes to call itself, has finally arrived. The follow-up to the immensely popular drag racing game CSR Racing is the first release from NaturalMotion since the studio's acquisition by Zynga in early 2014. [Read more] | Read more »
Nanuleu (Games)
Nanuleu 1.1 Device: iOS Universal Category: Games Price: $2.99, Version: 1.1 (iTunes) Description: Nanuleu is a strategy game where you take control of ancient magical trees that protect the land from an invading dark force. A... | Read more »

Price Scanner via

July 4th sale: $100 off 13-inch MacBook Airs
Amazon has 13″ MacBook Airs on sale for $100 off MSRP for a limited time. Shipping is free: - 13″ 1.6GHz/128GB MacBook Air (sku MMGF2LL/A): $899.99 $100 off MSRP - 13″ 1.6GHz/256GB MacBook Air (sku... Read more
Swiftpoint Launches Advanced Pivot, Tilt And...
Christchurch, New Zealand based Swiftpoint has announced the launch of its new generation computer mouse, The Z, on the crowdfunding website The company’s previous device, the... Read more
Clearance 12-inch Retina MacBooks, Apple refu...
Apple has Certified Refurbished 2015 12″ Retina MacBooks available starting at $929. Apple will include a standard one-year warranty with each MacBook, and shipping is free. The following... Read more
12-inch MacBooks available with free bundles...
Adorama has 12″ Retina MacBooks available including free shipping plus NY & NJ sales tax only. For a limited time, Adorama will include a free Apple USB-C to USB Adapter, free 4-Port USB Hub, and... Read more
Das Keyboard Unveils First Cloud-Connected Ke...
Austin, Texas based Das Keyboard has unveiled the newest addition to its family of high-performance mechanical keyboards with the introduction of the Das Keyboard 5Q on Kickstarter. Built with... Read more
13-inch 2.7GHz Retina MacBook Pros on sale fo...
Adorama has 13″ 2.7GHz Retina MacBook Pros on sale for up to $130 off MSRP. Shipping is free, and Adorama charges NY & NJ sales tax only: - 13″ 2.7GHz/128GB Retina MacBook Pro: $1169 $130 off -... Read more
New App Reminds Us to Put Down Our Phones and...
Mode, a new smartphone app that makes us more mindful of how we use our devices, debuts in the app stores today. The Mode app tracks time spent in different modes of day-to-day life without... Read more
ZuumSpeed Personalized Speedometer + HUD For...
RMKapps has announced the release and immediate availability of ZuumSpeed 1.0, its personalized speedometer plus heads up display for iOS devices. ZuumSpeed gives users over 18 custom fonts available... Read more
Apple refurbished clearance 15-inch Retina Ma...
Apple has Certified Refurbished 2014 15″ 2.2GHz Retina MacBook Pros available for $1609, $390 off original MSRP. Apple’s one-year warranty is included, and shipping is free. They have refurbished 15... Read more
9-inch 128GB Silver iPad Pro on sale for $50...
B&H Photo has the 9.7″ 128GB Silver Apple iPad Pro on sale for $699 including free shipping plus NY tax only. Their price is $50 off MSRP. Read more

Jobs Board

*Apple* Retail - Multiple Positions - Apple,...
Job Description: Sales Specialist - Retail Customer Service and Sales Transform Apple Store visitors into loyal Apple customers. When customers enter the store, Read more
*Apple* iPhone 6s and New Products Tester Ne...
…we therefore look forward to put out products to quality test for durability. Apple leads the digital music revolution with its iPods and iTunes online store, Read more
*Apple* Retail - Multiple Positions, Fort Wo...
Sales Specialist - Retail Customer Service and Sales Transform Apple Store visitors into loyal Apple customers. When customers enter the store, you're also the Read more
*Apple* Retail - Multiple Positions - Apple,...
Job Description: Sales Specialist - Retail Customer Service and Sales Transform Apple Store visitors into loyal Apple customers. When customers enter the store, Read more
*Apple* iPhone 6s and New Products Tester Ne...
…we therefore look forward to put out products to quality test for durability. Apple leads the digital music revolution with its iPods and iTunes online store, Read more
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.