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

Dropbox 193.4.5594 - Cloud backup and sy...
Dropbox is a file hosting service that provides cloud storage, file synchronization, personal cloud, and client software. It is a modern workspace that allows you to get to all of your files, manage... Read more
Google Chrome 122.0.6261.57 - Modern and...
Google Chrome is a Web browser by Google, created to be a modern platform for Web pages and applications. It utilizes very fast loading of Web pages and has a V8 engine, which is a custom built... Read more
Skype 8.113.0.210 - Voice-over-internet...
Skype is a telecommunications app that provides HD video calls, instant messaging, calling to any phone number or landline, and Skype for Business for productive cooperation on the projects. This... Read more
Tor Browser 13.0.10 - Anonymize Web brow...
Using Tor Browser you can protect yourself against tracking, surveillance, and censorship. Tor was originally designed, implemented, and deployed as a third-generation onion-routing project of the U.... Read more
Deeper 3.0.4 - Enable hidden features in...
Deeper is a personalization utility for macOS which allows you to enable and disable the hidden functions of the Finder, Dock, QuickTime, Safari, iTunes, login window, Spotlight, and many of Apple's... Read more
OnyX 4.5.5 - Maintenance and optimizatio...
OnyX is a multifunction utility that you can use to verify the startup disk and the structure of its system files, to run miscellaneous maintenance and cleaning tasks, to configure parameters in the... Read more

Latest Forum Discussions

See All

Zenless Zone Zero opens entries for its...
miHoYo, aka HoYoverse, has become such a big name in mobile gaming that it's hard to believe that arguably their flagship title, Genshin Impact, is only three and a half years old. Now, they continue the road to the next title in their world, with... | Read more »
Live, Playdate, Live! – The TouchArcade...
In this week’s episode of The TouchArcade Show we kick things off by talking about all the games I splurged on during the recent Playdate Catalog one-year anniversary sale, including the new Lucas Pope jam Mars After Midnight. We haven’t played any... | Read more »
TouchArcade Game of the Week: ‘Vroomies’
So here’s a thing: Vroomies from developer Alex Taber aka Unordered Games is the Game of the Week! Except… Vroomies came out an entire month ago. It wasn’t on my radar until this week, which is why I included it in our weekly new games round-up, but... | Read more »
SwitchArcade Round-Up: ‘MLB The Show 24’...
Hello gentle readers, and welcome to the SwitchArcade Round-Up for March 15th, 2024. We’re closing out the week with a bunch of new games, with Sony’s baseball franchise MLB The Show up to bat yet again. There are several other interesting games to... | Read more »
Steam Deck Weekly: WWE 2K24 and Summerho...
Welcome to this week’s edition of the Steam Deck Weekly. The busy season has begun with games we’ve been looking forward to playing including Dragon’s Dogma 2, Horizon Forbidden West Complete Edition, and also console exclusives like Rise of the... | Read more »
Steam Spring Sale 2024 – The 10 Best Ste...
The Steam Spring Sale 2024 began last night, and while it isn’t as big of a deal as say the Steam Winter Sale, you may as well take advantage of it to save money on some games you were planning to buy. I obviously recommend checking out your own... | Read more »
New ‘SaGa Emerald Beyond’ Gameplay Showc...
Last month, Square Enix posted a Let’s Play video featuring SaGa Localization Director Neil Broadley who showcased the worlds, companions, and more from the upcoming and highly-anticipated RPG SaGa Emerald Beyond. | Read more »
Choose Your Side in the Latest ‘Marvel S...
Last month, Marvel Snap (Free) held its very first “imbalance" event in honor of Valentine’s Day. For a limited time, certain well-known couples were given special boosts when conditions were right. It must have gone over well, because we’ve got a... | Read more »
Warframe welcomes the arrival of a new s...
As a Warframe player one of the best things about it launching on iOS, despite it being arguably the best way to play the game if you have a controller, is that I can now be paid to talk about it. To whit, we are gearing up to receive the first... | Read more »
Apple Arcade Weekly Round-Up: Updates an...
Following the new releases earlier in the month and April 2024’s games being revealed by Apple, this week has seen some notable game updates and events go live for Apple Arcade. What The Golf? has an April Fool’s Day celebration event going live “... | Read more »

Price Scanner via MacPrices.net

Apple Education is offering $100 discounts on...
If you’re a student, teacher, or staff member at any educational institution, you can use your .edu email address when ordering at Apple Education to take $100 off the price of a new M3 MacBook Air.... Read more
Apple Watch Ultra 2 with Blood Oxygen feature...
Best Buy is offering Apple Watch Ultra 2 models for $50 off MSRP on their online store this week. Sale prices available for online orders only, in-store prices may vary. Order online, and choose... Read more
New promo at Sams Club: Apple HomePods for $2...
Sams Club has Apple HomePods on sale for $259 through March 31, 2024. Their price is $40 off Apple’s MSRP, and both Space Gray and White colors are available. Sale price is for online orders only, in... Read more
Get Apple’s 2nd generation Apple Pencil for $...
Apple’s Pencil (2nd generation) works with the 12″ iPad Pro (3rd, 4th, 5th, and 6th generation), 11″ iPad Pro (1st, 2nd, 3rd, and 4th generation), iPad Air (4th and 5th generation), and iPad mini (... Read more
10th generation Apple iPads on sale for $100...
Best Buy has Apple’s 10th-generation WiFi iPads back on sale for $100 off MSRP on their online store, starting at only $349. With the discount, Best Buy’s prices are the lowest currently available... Read more
iPad Airs on sale again starting at $449 on B...
Best Buy has 10.9″ M1 WiFi iPad Airs on record-low sale prices again for $150 off Apple’s MSRP, starting at $449. Sale prices for online orders only, in-store price may vary. Order online, and choose... Read more
Best Buy is blowing out clearance 13-inch M1...
Best Buy is blowing out clearance Apple 13″ M1 MacBook Airs this weekend for only $649.99, or $350 off Apple’s original MSRP. Sale prices for online orders only, in-store prices may vary. Order... Read more
Low price alert! You can now get a 13-inch M1...
Walmart has, for the first time, begun offering new Apple MacBooks for sale on their online store, albeit clearance previous-generation models. They now have the 13″ M1 MacBook Air (8GB RAM, 256GB... Read more
Best Apple MacBook deal this weekend: Get the...
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 15-inch M3 MacBook Air (Midnight) on sale...
Amazon has the new 15″ M3 MacBook Air (8GB RAM/256GB SSD/Midnight) in stock and on sale today for $1249.99 including free shipping. Their price is $50 off MSRP, and it’s the lowest price currently... Read more

Jobs Board

Early Preschool Teacher - Glenda Drive/ *Appl...
Early Preschool Teacher - Glenda Drive/ Apple ValleyTeacher Share by Email Share on LinkedIn Share on Twitter Read more
Senior Software Engineer - *Apple* Fundamen...
…center of Microsoft's efforts to empower our users to do more. The Apple Fundamentals team focused on defining and improving the end-to-end developer experience in Read more
Relationship Banker *Apple* Valley Main - W...
…Alcohol Policy to learn more. **Company:** WELLS FARGO BANK **Req Number:** R-350696 **Updated:** Mon Mar 11 00:00:00 UTC 2024 **Location:** APPLE VALLEY,California Read more
Medical Assistant - Surgical Oncology- *Apple...
Medical Assistant - Surgical Oncology- Apple Hill WellSpan Medical Group, York, PA | Nursing | Nursing Support | FTE: 1 | Regular | Tracking Code: 200555 Apply Now Read more
Early Preschool Teacher - Glenda Drive/ *Appl...
Early Preschool Teacher - Glenda Drive/ Apple ValleyTeacher Share by Email Share on LinkedIn Share on Twitter Read more
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.