Merging tow documents using AltChunk
Home › Forums › Open-Xml-Sdk › Merging tow documents using AltChunk
This topic contains 0 replies, has 1 voice, and was last updated by ajaybabu.maddinani 8 years, 2 months ago.
-
AuthorPosts
-
September 23, 2016 at 9:15 am #3825
Hi Eric,
I am trying to merge document 1 to document 2 in place of a paragraph of document 2.
The Paragraph is appended dynamically to document 2.I am using altchunk and insertafter methods as below.
I am getting Operation is not valid due to current state of object at mainPart.Document.Body.InsertAfter(altChunk, mergeFieldParagraph);
Appreciate your help. Have been truck on this for 3 days.
public void FindAndReplaceMergeFieldsWithDocumentContent(Dictionary<string, string> documentsToMerge,bool bAppendMergeTags=true)
{
MainDocumentPart mainPart = this.MainDocumentPart;
int counter = 1;
foreach (var documentToMerge in documentsToMerge)
{
string altChunkId = “AltChunkId” + counter;
AlternativeFormatImportPart chunk = mainPart.AddAlternativeFormatImportPart(
AlternativeFormatImportPartType.WordprocessingML, altChunkId);
using (FileStream fileStream = File.Open(documentToMerge.Value, FileMode.Open))
{
chunk.FeedData(fileStream);
}
AltChunk altChunk = new AltChunk();
altChunk.Id = altChunkId;mainPart.Document.Body.AppendChild(new Paragraph(new Run(new Break() { Type = BreakValues.Page })));
//next document
var mergeFieldParagraph = FindParagraphWithMergeField(mainPart.Document.Body, documentToMerge.Key, bAppendMergeTags);
mainPart.Document.Body.InsertAfter(altChunk, mergeFieldParagraph);//Remove Merge Field Paragraph after document content is inserted
mergeFieldParagraph.RemoveAllChildren<Run>();
counter = counter + 1;
}
mainPart.Document.Save();
}public Paragraph FindParagraphWithMergeField(OpenXmlElement parent, string term, bool bAppendMergeTags = true)
{
if(bAppendMergeTags)
{
term = TemplateContentTag.MergeFieldStartTag + term + TemplateContentTag.MergeFieldEndTag;
}
//Merge Field is of format “«Section3»”. Get the paragraph containing this merge field
var result = parent.Descendants<Paragraph>().Where(t => t.InnerText.Contains(term)).FirstOrDefault();
return result;
} -
AuthorPosts
You must be logged in to reply to this topic.