scale the canvas based on the dimension of your destination rectangle:
# set a width height
w, h = 396, 244
# create a formattedString
txt = FormattedString()
# set a font
txt.font("Times")
# add some text
txt += "kweti"
#move it a bit
translate(100, 100)
# draw the black stroked rect
fill(None)
stroke(0)
rect(0, 0, w, h)
# create a path object
path = BezierPath()
# draw text into the path
path.text(txt)
# get the bounds of the path
minx, miny, maxx, maxy = path.bounds()
# get a scale value based on the bounding box
scaleX = w / (maxx - minx)
scaleY = h / (maxy - miny)
# pick the smallest one and shift up to the middle in the other direction
if scaleX < scaleY:
scale(scaleX)
shift = (h / scaleX - (maxy - miny)) / 2
translate(0, shift)
else:
scale(scaleY)
shift = (w / scaleY - (maxx - minx)) / 2
translate(shift, 0)
# translate witht the offset
translate(-minx, -miny)
# draw as text
text(txt, (0, 0))