TweetFollow Us on Twitter

The Perils Of PostScript

The Perils Of PostScript

SCOTT "ZZ" ZIMMERMAN

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.

PICK A FONT, ANY FONT

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);
VAR
    theFontID:  INTEGER;
    thePenLoc:  Point;
BEGIN
    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. *)
END;

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]).

ON WITH THE SHOW

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);
    VAR
        PSCommand   : Str255;
        CommandHdl  : Handle;
        CRString    : Str255;
        theError    : OSErr;
    BEGIN
        CRString := ' ';
        CRString[1] := CHR(13);
        PSCommand := theComment;
        PSCommand := CONCAT(PSCommand, CRString);
        theError := PtrToHand(POINTER(ORD(@PSCommand) + 1),
            CommandHdl,LENGTH(PSCommand));
        if theError <> noErr THEN BEGIN
            (* Handle the error! *)
        END;
        PicComment(PostScriptHandle, 
            LENGTH(PSCommand), CommandHdl);
        DisposHandle(CommandHdl);
    END;

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.');
        PenPat(ltGray);
        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).

SAVE THE POSTSCRIPT STATE

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);
        PenPat(ltGray);
        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

Latest Forum Discussions

See All

The Legend of Heroes: Trails of Cold Ste...
I adore game series that have connecting lore and stories, which of course means the Legend of Heroes is very dear to me, Trails lore has been building for two decades. Excitedly, the next stage is upon us as Userjoy has announced the upcoming... | Read more »
Go from lowly lizard to wicked Wyvern in...
Do you like questing, and do you like dragons? If not then boy is this not the announcement for you, as Loongcheer Game has unveiled Quest Dragon: Idle Mobile Game. Yes, it is amazing Square Enix hasn’t sued them for copyright infringement, but... | Read more »
Aether Gazer unveils Chapter 16 of its m...
After a bit of maintenance, Aether Gazer has released Chapter 16 of its main storyline, titled Night Parade of the Beasts. This big update brings a new character, a special outfit, some special limited-time events, and, of course, an engaging... | Read more »
Challenge those pesky wyverns to a dance...
After recently having you do battle against your foes by wildly flailing Hello Kitty and friends at them, GungHo Online has whipped out another surprising collaboration for Puzzle & Dragons. It is now time to beat your opponents by cha-cha... | Read more »
Pack a magnifying glass and practice you...
Somehow it has already been a year since Torchlight: Infinite launched, and XD Games is celebrating by blending in what sounds like a truly fantastic new update. Fans of Cthulhu rejoice, as Whispering Mist brings some horror elements, and tests... | Read more »
Summon your guild and prepare for war in...
Netmarble is making some pretty big moves with their latest update for Seven Knights Idle Adventure, with a bunch of interesting additions. Two new heroes enter the battle, there are events and bosses abound, and perhaps most interesting, a huge... | Read more »
Make the passage of time your plaything...
While some of us are still waiting for a chance to get our hands on Ash Prime - yes, don’t remind me I could currently buy him this month I’m barely hanging on - Digital Extremes has announced its next anticipated Prime Form for Warframe. Starting... | Read more »
If you can find it and fit through the d...
The holy trinity of amazing company names have come together, to release their equally amazing and adorable mobile game, Hamster Inn. Published by HyperBeard Games, and co-developed by Mum Not Proud and Little Sasquatch Studios, it's time to... | Read more »
Amikin Survival opens for pre-orders on...
Join me on the wonderful trip down the inspiration rabbit hole; much as Palworld seemingly “borrowed” many aspects from the hit Pokemon franchise, it is time for the heavily armed animal survival to also spawn some illegitimate children as Helio... | Read more »
PUBG Mobile teams up with global phenome...
Since launching in 2019, SpyxFamily has exploded to damn near catastrophic popularity, so it was only a matter of time before a mobile game snapped up a collaboration. Enter PUBG Mobile. Until May 12th, players will be able to collect a host of... | Read more »

Price Scanner via MacPrices.net

Apple is offering significant discounts on 16...
Apple has a full line of 16″ M3 Pro and M3 Max MacBook Pros available, Certified Refurbished, starting at $2119 and ranging up to $600 off MSRP. Each model features a new outer case, shipping is free... Read more
Apple HomePods on sale for $30-$50 off MSRP t...
Best Buy is offering a $30-$50 discount on Apple HomePods this weekend on their online store. The HomePod mini is on sale for $69.99, $30 off MSRP, while Best Buy has the full-size HomePod on sale... Read more
Limited-time sale: 13-inch M3 MacBook Airs fo...
Amazon has the base 13″ M3 MacBook Air (8GB/256GB) in stock and on sale for a limited time for $989 shipped. That’s $110 off MSRP, and it’s the lowest price we’ve seen so far for an M3-powered... Read more
13-inch M2 MacBook Airs in stock today at App...
Apple has 13″ M2 MacBook Airs available for only $849 today in their Certified Refurbished store. These are the cheapest M2-powered MacBooks for sale at Apple. Apple’s one-year warranty is included,... Read more
New today at Apple: Series 9 Watches availabl...
Apple is now offering Certified Refurbished Apple Watch Series 9 models on their online store for up to $80 off MSRP, starting at $339. Each Watch includes Apple’s standard one-year warranty, a new... Read more
The latest Apple iPhone deals from wireless c...
We’ve updated our iPhone Price Tracker with the latest carrier deals on Apple’s iPhone 15 family of smartphones as well as previous models including the iPhone 14, 13, 12, 11, and SE. Use our price... Read more
Boost Mobile will sell you an iPhone 11 for $...
Boost Mobile, an MVNO using AT&T and T-Mobile’s networks, is offering an iPhone 11 for $149.99 when purchased with their $40 Unlimited service plan (12GB of premium data). No trade-in is required... Read more
Free iPhone 15 plus Unlimited service for $60...
Boost Infinite, part of MVNO Boost Mobile using AT&T and T-Mobile’s networks, is offering a free 128GB iPhone 15 for $60 per month including their Unlimited service plan (30GB of premium data).... Read more
$300 off any new iPhone with service at Red P...
Red Pocket Mobile has new Apple iPhones on sale for $300 off MSRP when you switch and open up a new line of service. Red Pocket Mobile is a nationwide MVNO using all the major wireless carrier... Read more
Clearance 13-inch M1 MacBook Airs available a...
Apple has clearance 13″ M1 MacBook Airs, Certified Refurbished, available for $759 for 8-Core CPU/7-Core GPU/256GB models and $929 for 8-Core CPU/8-Core GPU/512GB models. Apple’s one-year warranty is... Read more

Jobs Board

DMR Technician - *Apple* /iOS Systems - Haml...
…relevant point-of-need technology self-help aids are available as appropriate. ** Apple Systems Administration** **:** Develops solutions for supporting, deploying, Read more
Operating Room Assistant - *Apple* Hill Sur...
Operating Room Assistant - Apple Hill Surgical Center - Day Location: WellSpan Health, York, PA Schedule: Full Time Sign-On Bonus Eligible Remote/Hybrid Regular Read more
Solutions Engineer - *Apple* - SHI (United...
**Job Summary** An Apple Solution Engineer's primary role is tosupport SHI customers in their efforts to select, deploy, and manage Apple operating systems and Read more
DMR Technician - *Apple* /iOS Systems - Haml...
…relevant point-of-need technology self-help aids are available as appropriate. ** Apple Systems Administration** **:** Develops solutions for supporting, deploying, Read more
Omnichannel Associate - *Apple* Blossom Mal...
Omnichannel Associate - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Apple Read more
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.