6

I am using reportlab to generate a pdf file. I has some problem when i draw a string on the pdf. how can i get the height of the string with TTFont?

the code:

# Register fonts. pdfmetrics.registerFont(ttfonts.TTFont('fz1', 'fz1.ttf')) pdfmetrics.registerFont(ttfonts.TTFont('fz3', 'fz3.ttf')) pdfmetrics.registerFont(ttfonts.TTFont('fz4', 'fz4.ttf')) pdfmetrics.registerFont(ttfonts.TTFont('fz5', 'fz5.ttf')) pdfmetrics.registerFont(ttfonts.TTFont('w5', 'w5.ttc')) def draw_text(canvas, fontName, fontSize, x, y, text, cmyk_color=None): t = canvas.beginText(x * mm, y * mm) t.setFont(fontName, fontSize) if cmyk_color is None: cmyk_color = (0, 0, 0, COLOR_DIV_RATIO) canvas.setFillColorCMYK(cmyk_color[0] / COLOR_DIV_RATIO, cmyk_color[1] / COLOR_DIV_RATIO, cmyk_color[2] / COLOR_DIV_RATIO, cmyk_color[3] / COLOR_DIV_RATIO) t.textLine(text) canvas.drawText(t) c.drawImage('f1.jpg', 0, 0, CANVAS_WIDTH * mm, CANVAS_HEIGHT * mm) draw_text(c, 'fz1', 15, mm2pixel(5), mm2pixel(45), u'This is a string') 

I can get the string's width by:

text_width = stringWidth(text, 'fz1', 15) 

but, how can i get the string's height?

1
  • 1
    I believe this is what the font size means already (15 would probably be 15 points high), though I'm willing to guess there's more to it and don't recall all the details at the moment Commented Oct 15, 2013 at 16:45

2 Answers 2

5

If you use a Paragraph then wrap it on the canvas, it will return to you the width and height that it will take up.

p = Paragraph(text, style=preferred_style) width, height = p.wrapOn(self.canvas, aW, aH) p.drawOn(self.canvas, x_pos, y_pos) 

aH = available Height aW = available Width

the style refers to a ParagraphStyle.

Sign up to request clarification or add additional context in comments.

Comments

5

Works perfectly (source):

from reportlab.pdfbase import pdfmetrics face = pdfmetrics.getFont(font).face string_height = (face.ascent - face.descent) / 1000 * font_size # canvas.setFont(font, font_size) 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.