3

I have multiple FlowDocuments that I would like to concatenate together. The method below doesn't have a return statement. What I would like to do is to turn the TextRange back into a FlowDocument.

private FlowDocument Concatenate(FlowDocument source, FlowDocument target)
{   using(MemoryStream ms = new MemoryStream())
    {
      TextRange tr = new TextRange(source.ContentStart, source.ContentEnd);
      tr.Save(ms, DataFormats.XamlPackage);
      ms.Seek(0, SeekOrigin.Begin);
      tr = new TextRange(target.ContentEnd, target.ContentEnd);
      tr.Load(ms, DataFormats.XamlPackage);
   }
}
B4ndt
  • 576
  • 2
  • 7
  • 15
  • I think the problem is that you are going to have a root for each or no root. I would try XML to read the contents from each and then XML to write the contents to 1. – paparazzo Feb 29 '12 at 23:32

2 Answers2

5

Since FlowDocuments are just basically block collections, it is possible, and much cleaner, to simply extract the collection from the source document as a list of blocks and then insert those into the target document. Make sure to extract the blocks using ToList() or else you will get an error along the lines of "object already belongs to another collection"

try this (untested):

'targetDocument is flowdocument that will be aggregate of both
'insertDocument contains document content you want to insert into target
 Dim insertBlocks As List(Of Block) = insertDocument.Blocks.ToList()
 targetDocument.Blocks.AddRange(insertBlocks)
TheZenker
  • 1,710
  • 1
  • 16
  • 29
2

A C# implementation of @TheZenker's answer (which has been tested):

public static FlowDocument MergedFlowDoc(IEnumerable<FlowDocument> fDocs)
{
    var fDoc = new FlowDocument();
    foreach (var doc in fDocs)
    {
        fDoc.Blocks.AddRange(doc.Blocks.ToList());
    }
    return fDoc;
}
Jim Simson
  • 2,774
  • 3
  • 22
  • 30