Persits Software, Inc. Knowledge Base Articles

HOWTO: Compute height of a text paragraph

Problem Description

To lay out dynamic content on a PDF page, it may sometimes be necessary to determine the height (vertical extent) of a text string spanning multiple lines.

This article shows how to determine the height of an arbitrary text paragraph.

Solution

Version 1.5+

Starting with Version 1.5, AspPDF offers the method PdfFont.GetParagraphHeight which dynamically calculates the height of a text paragraph:

...
strText = "Some long text string"
Set Font = Doc.Fonts("Arial")
Height = Font.GetParagraphHeight(strText, "width=150")

This method accepts the same parameters as PdfCell.AddText except that the Width parameter is required. It specifies the desired width of the text paragraph being drawn.

Versions Prior to 1.5

If you are using a version of AspPDF prior to 1.5, use a workaround described below.

The basic idea is to create a temporary single-cell table (1 row, 1 column) with the width equal to the desired width of the paragraph, and an arbitrarily small height (such as 5). We can then call the AddText method on the table's only cell with the Expand parameter set to True, which causes the cell to expand just enough to accommodate the text string.

After a successful call to AddText, we can retrieve the cell's new height (which matches the text paragraph's height) via the property Cell.Height. The table can be discarded afterwards.

Set Table = Doc.CreateTable("rows=1;cols=1;width=200;height=5")
Set Cell = Table(1, 1)
Cell.AddText strText, "expand=true", Font
Height = Cell.Height
Set Table = Nothing