0

I am using PyX to create rectangles and putting some (LaTex) text within the rectangle.

# python 3
from pyx import *
text.set(text.LatexRunner)
c = canvas.canvas()
c.stroke(path.rect(0, 0, 1, 1), [style.linewidth.Thick,
                                 color.rgb.red,
                                 deco.filled([color.rgb.green])])

c.text(0.25, 0.25, r"\LaTeX{}")

c.writePDFfile("text-centered") # creates a PDF file     

The above code snippet creates a PDF:

As you can see, the text is not aligned. It is possible to try manually until it is (visibly) centered, but this is problematic for obvious reasons.

My question: Is it possible to align the text centered (both horizontally and vertically) automatically?

hola
  • 930
  • 1
  • 17
  • 35

1 Answers1

2

just use

c.text(0.5, 0.5, r"\LaTeX{}", [text.halign.center, text.vshift.mathaxis])

see

for some documentation and examples

wobsta
  • 721
  • 4
  • 5
  • This solves the problem. However, I have a follow-up question: There are situations where the text width is larger than the rectangle. Is there any automatic way to resize the rectangle? *Do you think I should post this as a separate question?* – hola Jan 07 '19 at 08:30
  • Indeed, this basically is a new question. And it all depends on what you want to achieve. c.text(...) returns the text "object", which has attributes like width, height, depth, left, and right. Those are PyX length, but you can pass them to path items and path constructors. However, you might want to render the text first (use text.text(...)) and insert it to the canvas later on (c.insert(...)). You can apply a transformation here (like a translation for shifting). By that you can first get the extends, decide about the layout and then place it all to the canvas. – wobsta Jan 07 '19 at 11:25