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

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 »
Embark into the frozen tundra of certain...
Chucklefish, developers of hit action-adventure sandbox game Starbound and owner of one of the cutest logos in gaming, has released their roguelike deck-builder Wildfrost. Created alongside developers Gaziter and Deadpan Games, Wildfrost will... | Read more »
MoreFun Studios has announced Season 4,...
Tension has escalated in the ever-volatile world of Arena Breakout, as your old pal Randall Fisher and bosses Fred and Perrero continue to lob insults and explosives at each other, bringing us to a new phase of warfare. Season 4, Into The Fog of... | Read more »
Top Mobile Game Discounts
Every day, we pick out a curated list of the best mobile discounts on the App Store and post them here. This list won't be comprehensive, but it every game on it is recommended. Feel free to check out the coverage we did on them in the links below... | Read more »
Marvel Future Fight celebrates nine year...
Announced alongside an advertising image I can only assume was aimed squarely at myself with the prominent Deadpool and Odin featured on it, Netmarble has revealed their celebrations for the 9th anniversary of Marvel Future Fight. The Countdown... | Read more »
HoYoFair 2024 prepares to showcase over...
To say Genshin Impact took the world by storm when it was released would be an understatement. However, I think the most surprising part of the launch was just how much further it went than gaming. There have been concerts, art shows, massive... | Read more »
Explore some of BBCs' most iconic s...
Despite your personal opinion on the BBC at a managerial level, it is undeniable that it has overseen some fantastic British shows in the past, and now thanks to a partnership with Roblox, players will be able to interact with some of these... | Read more »
Play Together teams up with Sanrio to br...
I was quite surprised to learn that the massive social network game Play Together had never collaborated with the globally popular Sanrio IP, it seems like the perfect team. Well, this glaring omission has now been rectified, as that instantly... | Read more »

Price Scanner via MacPrices.net

B&H has 13-inch M2 MacBook Airs with 16GB...
B&H Photo has 13″ MacBook Airs with M2 CPUs, 16GB of memory, and 256GB of storage in stock and on sale for $1099, $100 off Apple’s MSRP for this configuration. Free 1-2 day delivery is available... Read more
14-inch M3 MacBook Pro with 16GB of RAM avail...
Apple has the 14″ M3 MacBook Pro with 16GB of RAM and 1TB of storage, Certified Refurbished, available for $300 off MSRP. Each MacBook Pro features a new outer case, shipping is free, and an Apple 1-... Read more
Apple M2 Mac minis on sale for up to $150 off...
Amazon has Apple’s M2-powered Mac minis in stock and on sale for $100-$150 off MSRP, each including free delivery: – Mac mini M2/256GB SSD: $499, save $100 – Mac mini M2/512GB SSD: $699, save $100 –... Read more
Amazon is offering a $200 discount on 14-inch...
Amazon has 14-inch M3 MacBook Pros in stock and on sale for $200 off MSRP. Shipping is free. Note that Amazon’s stock tends to come and go: – 14″ M3 MacBook Pro (8GB RAM/512GB SSD): $1399.99, $200... Read more
Sunday Sale: 13-inch M3 MacBook Air for $999,...
Several Apple retailers have the new 13″ MacBook Air with an M3 CPU in stock and on sale today for only $999 in Midnight. These are the lowest prices currently available for new 13″ M3 MacBook Airs... Read more
Multiple Apple retailers are offering 13-inch...
Several Apple retailers have 13″ MacBook Airs with M2 CPUs in stock and on sale this weekend starting at only $849 in Space Gray, Silver, Starlight, and Midnight colors. These are the lowest prices... Read more
Roundup of Verizon’s April Apple iPhone Promo...
Verizon is offering a number of iPhone deals for the month of April. Switch, and open a new of service, and you can qualify for a free iPhone 15 or heavy monthly discounts on other models: – 128GB... Read more
B&H has 16-inch MacBook Pros on sale for...
Apple 16″ MacBook Pros with M3 Pro and M3 Max CPUs are in stock and on sale today for $200-$300 off MSRP at B&H Photo. Their prices are among the lowest currently available for these models. B... Read more
Updated Mac Desktop Price Trackers
Our Apple award-winning Mac desktop price trackers are the best place to look for the lowest prices and latest sales on all the latest computers. Scan our price trackers for the latest information on... Read more
9th-generation iPads on sale for $80 off MSRP...
Best Buy has Apple’s 9th generation 10.2″ WiFi iPads on sale for $80 off MSRP on their online store for a limited time. Prices start at only $249. Sale prices for online orders only, in-store prices... Read more

Jobs Board

*Apple* Systems Administrator - JAMF - Activ...
…**Public Trust/Other Required:** None **Job Family:** Systems Administration **Skills:** Apple Platforms,Computer Servers,Jamf Pro **Experience:** 3 + years of Read more
Liquor Stock Clerk - S. *Apple* St. - Idaho...
Liquor Stock Clerk - S. Apple St. Boise Posting Begin Date: 2023/10/10 Posting End Date: 2024/10/14 Category: Retail Sub Category: Customer Service Work Type: Part Read more
Top Secret *Apple* System Admin - Insight G...
Job Description Day to Day: * Configure and maintain the client's Apple Device Management (ADM) solution. The current solution is JAMF supporting 250-500 end points, Read more
Sonographer - *Apple* Hill Imaging Center -...
Sonographer - Apple Hill Imaging Center - Evenings Location: York Hospital, York, PA Schedule: Full Time Sign-On Bonus Eligible Remote/Hybrid Regular Apply Now Read more
Beauty Consultant - *Apple* Blossom Mall -...
Beauty Consultant - 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.