Free Support Forum - aspose.com

Merging Word Documents using <Image:> mergefields

Hi, I've this problem: there's a db field byte() containing word documents, and I need to embed in a unique merge document; I'm trying to use mergefields, but I need some hints on the best way to do this. Can you help me? thanks

Regards,

Tommaso

In other words, I'd want to reproduce Word field behavior, just using Aspose.Word API and documents in db byte() field. It's possible?

Regards,

Tommaso

Try using the following MergeField handler:

private void MergeFieldHandler(object sender, MergeFieldEventArgs e)

{

// if the value for the merge field is a BLOB

if((e.FieldValue as byte[]) != null)

{

DocumentBuilder builder = new DocumentBuilder(e.Document);

builder.MoveToMergeField(e.DocumentFieldName);

// Make document from the blob and insert its contents to merged document

InsertDocument(builder.CurrentParagraph, new Document(new MemoryStream((byte[])e.FieldValue)));

e.Text = "";

}

}

public void InsertDocument(Node node, Document doc)

{

Document dstDoc = node.Document;

Section insertedSection;

int index;

if(node.GetAncestor(typeof(Cell))!=null || node.GetAncestor(typeof(Shape))!=null)

{

// Insertion point is tracked to Cell or Shape level:

// - insert appended document on node by node basis.

index = node.ParentNode.ChildNodes.IndexOf(node);

foreach(Section section in doc.Sections)

{

foreach(Node sourceNode in section.Body.ChildNodes)

{

// Only Paragraph or Table nodes can be inserted into Cell or Shape

if(sourceNode is Paragraph || sourceNode is Table)

{

// Do not insert node if it is a last empty paragarph in the section.

if(sourceNode is Paragraph && sourceNode == section.Body.LastChild && !sourceNode.HasInnerText)

break;

Node insertedNode = dstDoc.ImportNode(sourceNode, true, ImportFormatMode.KeepSourceFormatting);

node.ParentNode.ChildNodes.Insert(index++, insertedNode);

}

}

}

}

else

{

// Insertion point is tracked to Section.Body level:

// - insert appended document on section by section basis.

Section dstSection;

Body body = (Body)node.GetAncestor(typeof(Body));

if(body.LastChild!=node)

{

DocumentBuilder builder = new DocumentBuilder(dstDoc);

builder.MoveTo(node);

builder.InsertBreak(BreakType.SectionBreakContinuous);

dstSection = builder.CurrentParagraph.ParentSection;

}

else

{

dstSection = (Section)node.GetAncestor(typeof(Section));

}

index = dstDoc.Sections.IndexOf(dstSection);

int index0 = index;

foreach(Section section in doc.Sections)

{

insertedSection = (Section)dstDoc.ImportNode(section, true, ImportFormatMode.KeepSourceFormatting);

//insertedSection.ClearHeadersFooters();

dstDoc.Sections.Insert(index++, insertedSection);

}

dstDoc.Sections[index0].PageSetup.SectionStart = SectionStart.Continuous;

}

}

Thank you a lot, it works well Smile [:)]. Aspose.Words is a very useful and nice tool

Best Regards

Tommaso