Search code examples
pdfpdf-generationalignmenttext-alignment

How to set horizontal or vertical alignment Text in PDF?


i am generating a PDF, and i am outputting some text, e.g.:

BT
  /F1 7 Tf
  586 406 Td
  (Date Shipped:) Tj
ET

A quick primer on the PDF programming language:

  • BT: begin text block
  • /F1 7 Tf: Select font #1 (which in my case is Helvetica), and use font size of 7 point
  • 586 406 Td Move the current location to (x=586 pt, y=406 pt)
  • (Date Shipped:) Tj: Render the text Date Shipped:
  • ET: end text block

That text is now always rendered at location (586,406), with the bottom left of the text block at that location:

enter image description here

What i want is that point to define the top center point:

enter image description here

Because i do not know the size of the rendered text; i cannot simply fudge things up/down/left/right to try to make up for it.

How can i indicate in a PDF some text's "alignment"?


Solution

  • You cannot. PDF producing software needs to know the font metrics to produce formatted output.

    As you know that you selected Helvetica at size 7 and you also know the current character and word spacing values, you can easily calculate the size of the rendered text.

    The font metrics of the standard 14 fonts are available here.

    You may want to read the PDF specification (made available here), especially the chapter on text rendering.