I could able to successfully insert the source word document into destination word document specified content control by the below mentioned code when the destination document is closed.
WmlDocument sdoc = new WmlDocument(@"C:\Users\indipat3\Desktop\Name.docx");
sdoc.SaveAs(@"C:\Users\indipat3\Desktop\Name_Mod.docx");
WmlDocument doc1 = new WmlDocument(@"C:\Users\indipat3\Desktop\Name_Mod.docx");
using (System.IO.MemoryStream mem = new System.IO.MemoryStream())
{
mem.Write(doc1.DocumentByteArray, 0, doc1.DocumentByteArray.Length);
using (WordprocessingDocument doc = WordprocessingDocument.Open(mem, true))
{
XDocument xDoc = doc.MainDocumentPart.GetXDocument();
XElement contentcontrolpar = xDoc
.Root
.Descendants(W.sdt)
.Where(sdt => (string)sdt
.Elements(W.sdtPr)
.Elements(W.tag)
.Attributes(W.val)
.FirstOrDefault() == "Doc1")
.FirstOrDefault()
.Elements(W.sdtContent)
.Elements(W.p)
.FirstOrDefault();
if (contentcontrolpar != null)
{
contentcontrolpar.ReplaceWith(
new XElement(PtOpenXml.Insert,
new XAttribute("Id", "Doc1")));
}
doc.MainDocumentPart.PutXDocument();
}
doc1.DocumentByteArray = mem.ToArray();
doc1.Save();
}
string outFileName = @"C:\Users\indipat3\Desktop\Name_Mod.docx";
File.Delete(outFileName);
List<OpenXmlPowerTools.Source> sources = new List<OpenXmlPowerTools.Source>()
{
new OpenXmlPowerTools.Source(doc1, true),
new OpenXmlPowerTools.Source(new WmlDocument(@"C:\Users\indipat3\Desktop\Insert.docx"),"Doc1"),
};
DocumentBuilder.BuildDocument(sources, outFileName);
Microsoft.Office.Interop.Word.Application app = new Microsoft.Office.Interop.Word.Application();
Microsoft.Office.Interop.Word.Document td = app.Documents.Open(outFileName);
Microsoft.Office.Interop.Word.Document sd = app.Documents.Open(@"C:\Users\indipat3\Desktop\Name.docx");
app.Visible = false;
Stream tdps = OpcHelper.GetPackageStreamFromRange(td.Range());
Stream sdps = OpcHelper.GetPackageStreamFromRange(sd.Range());
XDocument mdoc = OpcHelper.OpcToFlatOpc(Package.Open(tdps));
sd.Range().InsertXML(mdoc.ToString());
But however i want to insert the source document into destination document content control when the destination document is open (Because of VSTO application). Can any one have the solution or procedure for modifying the active document using DocumentBuilder.