Hi,
I am trying to layout a dynamically generated tabular report. I have code like this
var size = new System.Drawing.Font(systemFont, bodyFontSize);
var textSize = TextRenderer.MeasureText(headerText, size);
// Add columns to the table
table.Columns.Add(textSize.Width);
The point is to get how wide the column should be in a table and provide that information to the table setup.
However I cant find an equivalent of the MeasureText in the api, how would I go about getting the dimensions of an arbitrary string in this instance
Text Dimensions
Re: Text Dimensions
Support · Mar 31, 2016Hello,
GetTextWidth
is the method available in our API that would allow you measure the width of text for a specified font and font size. GetTextWidth is available on both Font
and OpenTypeFont
classes.
When you set the table column width, you may have to take into account the cell attributes (like cell border width and cell padding) along with text width. Here is the sample code:
Document document = new Document();
Page page = new Page();
document.Pages.Add(page);
Table2 table = new Table2(0, 0, 600, 600);
table.CellDefault.Border.Color = RgbColor.Red;
string headerText = "This is to test Header text width";
//Calculating text width.
//Load the appropriate system font.
Font font = Font.LoadSystemFont("Verdana");
//Or load the font file using OpenTypeFont class.
//OpenTypeFont font = new OpenTypeFont("path to font file");
//check the width of the text.
float textwidth = font.GetTextWidth(headerText, 16);
float cellPadding = (float)table.CellDefault.Padding.Left + (float)table.CellDefault.Padding.Right;
float cellBorderWidth = (float)table.CellDefault.Border.Left.Width + (float)table.CellDefault.Border.Right.Width;
float cloumnWidht = textwidth + cellPadding + cellBorderWidth;
table.Columns.Add(cloumnWidht);
table.Columns.Add(90);
table.Columns.Add(90);
// Add rows to the table and add cells to the rows
Row2 row1 = table.Rows.Add(40, font, 16, RgbColor.Black, RgbColor.Gray);
row1.Cells.Add(headerText);
row1.Cells.Add("header 2");
row1.Cells.Add("header 3");
// Add the table to the page
page.Elements.Add(table);
// Save the PDF
document.Draw(@"C:\Temp\MyDocument.pdf");
Thanks,
ceTe Software Support Team.