0

I'm in the process of trying to print out a FlowDocument that is being viewed by the user. I wrote a routine to create a copy of the original document so that changes (from the PrintDialog) don't get reflected into the DocumentViewer.

Unfortunately, my copy seems to have lost all of the information bound to its fields. I've tried resetting the DataContext but the copy's IsLoaded property is still coming back false, leading me to believe that the binding isn't occuring.

Any ideas?

Here's the code I'm using to copy the document:

private static void AddDocument(FlowDocument from, FlowDocument to)
{
    TextRange tr = new TextRange(from.ContentStart, from.ContentEnd);

    using (System.IO.MemoryStream ms = new System.IO.MemoryStream())
    {
        TextRange tr2 = null;

        System.Windows.Markup.XamlWriter.Save(tr, ms);
        tr.Save(ms, DataFormats.XamlPackage, true);
        tr2 = new TextRange(to.ContentEnd, to.ContentEnd);
        tr2.Load(ms, DataFormats.XamlPackage);
    }
}

And here's the code I'm using to print the document:

public static void PrintFlowDocument(FlowDocument fd, string title)
{
    PrintDialog pd = new PrintDialog();
    IDocumentPaginatorSource idps = null;
    FlowDocument flowDoc = new FlowDocument();

    AddDocument(fd, flowDoc);

    flowDoc.DataContext = fd.DataContext;
    flowDoc.PageHeight = pd.PrintableAreaHeight;
    flowDoc.PageWidth = pd.PrintableAreaWidth;
    flowDoc.PagePadding = new Thickness(50);
    flowDoc.ColumnGap = 0;
    flowDoc.ColumnWidth = pd.PrintableAreaWidth;


    idps = flowDoc;

    if (pd.ShowDialog() == true)
    {
        pd.PrintDocument(idps.DocumentPaginator, title);
    }
}

Thanks in advance,
Sonny

Sonny Boy
  • 7,848
  • 18
  • 76
  • 104

2 Answers2

0

Notice some off about this line?

tr2 = new TextRange(to.ContentEnd, to.ContentEnd);
paparazzo
  • 44,497
  • 23
  • 105
  • 176
0

I had similar issues and found the forcing the document creation to a background thread gave the binding an opportunity to fire. Otherwise, it would not happen on the UI thread.

So, if your copy document method were a function it would be something like this:

            Dim flowDoc As FlowDocument = 
                DirectCast(<ViewInstance>.UIDispatcher.Invoke(Function() 
                               AddFlowDocument(fd),
                               Windows.Threading.DispatcherPriority.Background), 
                           FlowDocument)
TheZenker
  • 1,710
  • 1
  • 16
  • 29