Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to center rotated text on page in PostScript

I put text Sample on every PDF page using the following PostScript code:

<<
   /EndPage {
   exch pop 2 lt { 
     gsave
     /Arial-Bold 120 selectfont
     .5 setgray 100 100 moveto 45 rotate (Sample) show
     grestore
     true}
     {false}
     ifelse
   } bind
>> setpagedevice

This puts text on [100; 100] position. But I need to center this text (accounting text is rotated).

How do I align this 45° rotated text in the center of a page?

like image 393
radistao Avatar asked Sep 01 '25 20:09

radistao


1 Answers

You can use false charpath flattenpath pathbbox to get the bounding box of the text. If the currentpoint is 0 0 when you do this, then the lower-left coordinates will be pretty close to 0 0, so the upper-right coordinates describe the width and height of the text. So you just move to the desired center-point and back-up by making a relative move to (-width/2, -height/2).

Since the center of rotation is also the center-point, you need to translate there before rotating.

%!
/w 612 def
/h 792 def
/Helvetica-Bold 120 selectfont

w .5 mul h .5 mul translate
0 0 moveto
(Sample) false charpath flattenpath pathbbox % llX llY urX urY
4 2 roll pop pop % urX urY

0 0 moveto
45 rotate
-.5 mul exch -.5 mul exch % -wid/2 -ht/2
rmoveto
(Sample) show

For more accuracy, replace 4 2 roll pop pop with

exch % llX llY urY urX
4 1 roll % urX llX llY urY
exch sub % urX llX urY-llY
3 1 roll % urY-llY urX llX
sub exch % urX-llX urY-llY

And then the point can be anywhere (but there does need to be a currentpoint since charpath builds a path just like show does, even though pathbbox destroys it immediately; so you need some kind of moveto).

like image 105
luser droog Avatar answered Sep 05 '25 20:09

luser droog