0

I'm trying to determine the size of the textframe that will be needed for a block of text. This is to then be exported for an InDesign script to create the page. All in a console application.

I've tried to create a WPF TextBlock and assign the Text and a Width, but the Height and ActualHeight is NaN.

How can I determine the size of a textframe that will be needed for some text? Is using a WPF / Winforms textblock the best solution (to try and take advantage of existing code), or is there some other, better workflow?

Sinatr
  • 20,892
  • 15
  • 90
  • 319
user3791372
  • 4,445
  • 6
  • 44
  • 78
  • You may get help faster if you explain better what is *textframe* (I don't know what is `InDesign`). It could be a simple question (as you tagged it with `console`), but I have no clues what are you asking. Can you provide a code? A picture? Something to understand what is the problem? As per WPF `TextBlock`, you can't obtain size until layouting pass. You can try to [force](https://msdn.microsoft.com/en-us/library/system.windows.uielement.updatelayout(v=vs.110).aspx) it. – Sinatr May 09 '16 at 14:14
  • A textframe is simply a Desktop Publishing term for a box of text. For this example, I simply want to get the needed text block height from a defined text block width for a block of text. – user3791372 May 09 '16 at 14:20

1 Answers1

0

There are two classes in C# that are used to draw text. TextRenderer and Graphics.

TextRenderer uses GDI to render the text, whereas Graphics uses GDI+. The two use a slightly different method for laying out text.

You can make use of Graphics.MeasureString or TextRenderer.MeasureText

Example

using( Graphics g = Graphics.FromHwnd(IntPtr.Zero) )
{
     SizeF size = g.MeasureString("some text", SystemFonts.DefaultFont);
}

For your case I would suggest using TextRenderer. Text wrapping example -

var size = TextRenderer.MeasureText(text, font, new Size(width, height), TextFormatFlags.WordBreak);

The third argument is size of the drawing rectangle. You can pass height as 0 if you don't know it.

A G
  • 21,087
  • 11
  • 87
  • 112