I'm trying to add HTML content to DOCX file using OpenXML altchunk approach using C#. The below sample code works fine and appends the HTML content to the end of the document. My requirement is to add HTML content at a specific place in the document, like inside a table cell or inside a paragraph, or search and replace a specific string with an HTML string or placeholders marked using content controls. Can you please point me to some sample example or share few suggestions. Please let me know if you need more info.
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Linq;
using DocumentFormat.OpenXml.Packaging;
using OpenXmlPowerTools;
using DocumentFormat.OpenXml.Wordprocessing;
using DocumentFormat.OpenXml;
using System.Xml;
namespace Docg2
{
class Program
{
static void Main(string[] args)
{
testaltchunk();
}
public static void testaltchunk()
{
XNamespace w = "http://schemas.openxmlformats.org/wordprocessingml/2006/main";
XNamespace r = "http://schemas.openxmlformats.org/officeDocument/2006/relationships";
using (WordprocessingDocument myDoc = WordprocessingDocument.Open("../../Test3.docx", true))
{
string html =
@"<html>
<head/>
<body>
<h1>Html Heading</h1>
<p>This is an html document in a string literal.</p>
</body>
</html>";
string altChunkId = "AltChunkId1";
MainDocumentPart mainPart = myDoc.MainDocumentPart;
AlternativeFormatImportPart chunk = mainPart.AddAlternativeFormatImportPart("application/xhtml+xml", altChunkId);
using (Stream chunkStream = chunk.GetStream(FileMode.Create, FileAccess.Write))
using (StreamWriter stringStream = new StreamWriter(chunkStream))
stringStream.Write(html);
XElement altChunk = new XElement(w + "altChunk", new XAttribute(r + "id", altChunkId));
XDocument mainDocumentXDoc = GetXDocument(myDoc);
mainDocumentXDoc.Root
.Element(w + "body")
.Elements(w + "p")
.Last()
.AddAfterSelf(altChunk);
SaveXDocument(myDoc, mainDocumentXDoc);
}
}
private static void SaveXDocument(WordprocessingDocument myDoc, XDocument mainDocumentXDoc)
{
// Serialize the XDocument back into the part
using (var str = myDoc.MainDocumentPart.GetStream(FileMode.Create, FileAccess.Write))
using (var xw = XmlWriter.Create(str))
mainDocumentXDoc.Save(xw);
}
private static XDocument GetXDocument(WordprocessingDocument myDoc)
{
// Load the main document part into an XDocument
XDocument mainDocumentXDoc;
using (var str = myDoc.MainDocumentPart.GetStream())
using (var xr = XmlReader.Create(str))
mainDocumentXDoc = XDocument.Load(xr);
return mainDocumentXDoc;
}
}
}