10

In WPF, in order to add a FixedPage to a FixedDocument in code one needs to:

var page = new FixedPage();
var pageContent = new PageContent();

((IAddChild)pageContent).AddChild(page);

This appears to be the only way, however:

  • The MSDN documentation explicitly says one shouldn't do this ('This API supports the .NET Framework infrastructure and is not intended to be used directly from your code.'- PageContent.IAddChild.AddChild Method).

  • It's ugly to have to cast to an explicit interface implementation in order to add the content to PageContent.

  • It's not simple to perform the basic operation of PageContent.

The documentation doesn't actually explain how to do this and I couldn't find any other information on how to do it. Is there another way? A 'correct' way?

nicodemus13
  • 2,258
  • 2
  • 19
  • 31

1 Answers1

13

According to MSDN documentation, you simply add a FixedPage object to the PageContent.Child property and then add that to the FixedDocument by calling the FixedDocument.Pages.Add method.

For instance:

public FixedDocument RenderDocument() 
{
    FixedDocument fd = new FixedDocument();
    PageContent pc = new PageContent();
    FixedPage fp = new FixedPage();
    TextBlock tb = new TextBlock();

    //add some text to a TextBox object
    tb.Text = "This is some test text";
    //add the text box to the FixedPage
    fp.Children.Add(tb);
    //add the FixedPage to the PageContent 
    pc.Child = fp;
    //add the PageContent to the FixedDocument
    fd.Pages.Add(pc);

    return fd;
}
dtesenair
  • 696
  • 6
  • 8
  • Thanks, where's the documentation? – nicodemus13 Apr 17 '13 at 21:19
  • Check out the example at the bottom of this page: http://msdn.microsoft.com/en-us/library/system.windows.documents.pagecontent%28v=vs.100%29.aspx – dtesenair Jul 03 '13 at 17:32
  • when writing pc.Child it shows error. its a get method not set – Sivajith Oct 20 '14 at 11:28
  • 1
    The MSDN documentation says the `PageContent.Child` property "Gets or **sets** the FixedPage associated with this PageContent." Here's the link: https://msdn.microsoft.com/en-us/library/system.windows.documents.pagecontent.child(v=vs.110).aspx – dtesenair Apr 17 '15 at 16:07
  • 1
    The `PageContent.Child` property supports both `get` and `set` at .NET 4 but only `get` at .NET 3.5 – Brian THOMAS Jul 27 '15 at 13:57
  • Try this:- ((System.Windows.Markup.IAddChild)pageContent).AddChild(fixedPage); – The Lonely Coder Oct 19 '15 at 14:33
  • what about PageContent.Source ? "The element has a single required attribute, Source, which refers to a FixedPage part" – juFo Nov 14 '18 at 14:25