Skip to main content

PdfGraphics.MeasureString(String, Font) Method

Measures the specified string when drawn with specified font parameters.

Namespace: DevExpress.Pdf

Assembly: DevExpress.Pdf.v23.2.Drawing.dll

NuGet Package: DevExpress.Pdf.Drawing

Declaration

public SizeF MeasureString(
    string text,
    Font font
)

Parameters

Name Type Description
text String

A text to measure.

font Font

An object that defines font parameters.

Returns

Type Description
SizeF

The string’s measured size.

Remarks

Use this method to calculate a size of the drawn text. Use the returned SizeF object to calculate a page area or a point where you can draw text.

The MeasureString method overload measures a string with 96 DPI. Use the PdfGraphics.MeasureString(String, Font, PdfStringFormat, Single, Single) method overload to obtain text size with 72 DPI to calculate its size on a PDF page.

The code sample below uses the MeasureString method to draw text in the page center:

draw string result

using DevExpress.Pdf;
using System.Drawing;
//...

using (var processor = new PdfDocumentProcessor())
{
    processor.CreateEmptyDocument();
    using (PdfGraphics graphics = processor.CreateGraphics())
    {
        // Obtain the first document page
        PdfPage page = processor.AddNewPage(PdfPaperSize.A4);
        PdfRectangle pageSize = page.CropBox;

        // Specify text to draw
        string text = "PDF Document API";
        using (SolidBrush textBrush = new SolidBrush(Color.FromArgb(255, Color.DarkOrange)))
        {
            using (Font font = new Font("Segoe UI", 20, FontStyle.Regular))
            {
                // Calculate text size
                SizeF textSize = graphics.MeasureString(text, font);

                // Calculate a point where to draw text
                PointF textPoint =
                    new PointF((float)((pageSize.Width - textSize.Width) / 2), (float)((pageSize.Height - textSize.Height) / 2));

                // Draw text at the calculated point
                graphics.DrawString(text, font, textBrush, textPoint);

                // Add graphics content to the page foreground
                graphics.AddToPageForeground(page, 72, 72);
            }
        }
    }
    processor.SaveDocument("result.pdf");
}
See Also