.netwpffontstypesetting

How to get a scalable image representation from WPF controls?


I'm trying to "render" text outlines in WPF to from a rich text source.

In many cases, the TextFormatter class does what I want, as in this snippet:

var tf = new Typeface(
  new System.Windows.Media.FontFamily("Pericles"),
  FontStyles.Normal,
  FontWeights.Normal,
  new FontStretch()
);

var brush = new SolidColorBrush(Colors.Black);

var ftext = new FormattedText(
  text,
  CultureInfo.CurrentCulture,
  FlowDirection.LeftToRight,
  tf,
  72,
  brush
);

var geometry = ftext.BuildGeometry(new Point());

Here, I convert a piece of text to it's outlines (Geometry) in a specific typeface and size.

The FormattedText class has some limitations though. There is no way to get the paragraph formatting of FlowDocuments or OpenType features available from the Typography class, for example. There is generally a much more limited control over what it renders when compared to what I could do with a RichTextBox or arbitrary ui elements.

That's why I'm looking for a way to "render" arbitrary ui elements (or at least proper FlowDocuments) into outlines the same way I did with normal text in the snippet.

I'm not looking for a bitmap image - I'm interested in a scalable representation, for example something like a Geometry instance.

I suspect it might be possible because I know printing does a conversion of arbitrary xaml to a scalable image representation. I just don't want it actually printed.

Does anybody have any ideas?


Solution

  • I think I found a way myself:

    WPF allows to render in an XpfDocument without needing that document to be printed or stored on disk. It can be a document initialized on a memory stream. It is then "only" a matter of re-opening it and parse the xaml inside.

    A bit tricky in the details perhaps, but certainly possible.