B4ndt
B4ndt

Reputation: 586

How to concatenate multiple FlowDocuments together into 1 FlowDocument

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);
   }
}

Upvotes: 3

Views: 2768

Answers (2)

Jim Simson
Jim Simson

Reputation: 2872

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;
}

Upvotes: 2

TheZenker
TheZenker

Reputation: 1740

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)

Upvotes: 5

Related Questions