I need to determine the height of a string (in given scale and font) in postscript.
/Helvetic-Oblique findfont
10 scalefont
setfont
10 10 1 0 360 arc fill
10 10 moveto (test) dup stringwidth pop 2 div neg 0 rmoveto show
will print test centered horizontally (but not yet vertically) at (10,10). (to see this, I also show a small circle at 10,10). I also need to determine the string height to center the text vertically as well, but I cant find a function for it.
Are you familiar with the PostScript code you’re using? Or is it just blindly copied and pasted from someplace? If you want to understand it, you should google for “PostScript Language Reference” or “Red Book” or “PLRM”. These resources are available as PDFs from Adobe.
Your PostScript snippet uses the following steps:
(test)places the string “test” on the top of the stack.dupduplicates the topmost item on the stack. (You’ll now have the string twice on the stack.)stringwidth. After this operator is executed, the topmost “test” string will have been consumed, and two values will have been added to the stack instead: the string’s height (topmost) and the string’s width (second from top). [Update: Actually, “string’s height” isn’t entirely correct — it’s rather the vertical offset of the current point after finishing to draw the string…]pop. This simply deletes the topmost value on the stack. Now only string’s width remains on the top of the stack.2 divdivides that value by 2 and leaves the result (half the stringwidth).negnegates the topmost value on the stack. Now that negative value is topmost on the stack.0places the value “0” on top of the stack.rmovetothen consumes the two topmost values on the stack and moves the current point by that distance (half the string’s width) to the left.showconsumes the first “test” string that remained all the time at the bottom of the stack and “shows” it.So what would work to take into account the string’s height? Try as your last line:
To understand my changes look up the meaning of
charpath,div,exch,pathbbox,rollandsuboperators in The Red Book.This command uses Ghostscript to create a PDF file on Windows from the code (easier to view and check results):
On Linux use:
Better readable forms are:
and