I have a webpart . I insert InputFormTextBox into webpart.

I want save InputFormTextBox.text into word file with formating.

How do insert HTML into word document?


1 Answer 1


The altChunk markup tells the consuming application to import content into the document.

I use this code:

 XNamespace w =
    XNamespace r =
    File.Copy("E:\\Test.docx", "E:\\Test3.docx");
    using (WordprocessingDocument myDoc =
       WordprocessingDocument.Open("E:\\Test3.docx", true))
        string html =
           <p>        To<em> learn</em> more a<em>bout<strong> </strong> </em><strong>ASP.</strong>NET vi<span >sit jh kj</span> h</p> <strong>,j jlkjlj;lk;</strong>
        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))
        XElement altChunk = new XElement(w + "altChunk",
            new XAttribute(r + "id", altChunkId)
        XDocument mainDocumentXDoc = GetXDocument(myDoc);
            .Element(w + "body")
            .Elements(w + "p")
        SaveXDocument(myDoc, mainDocumentXDoc);

    private static void SaveXDocument(WordprocessingDocument myDoc, XDocument mainDocumentXDoc)
    // Serialize the XDocument back into the part
    using (Stream str = myDoc.MainDocumentPart.GetStream(
        FileMode.Create, FileAccess.Write))
    using (XmlWriter xw = XmlWriter.Create(str))
private static XDocument GetXDocument(WordprocessingDocument myDoc)
    // Load the main document part into an XDocument
    XDocument mainDocumentXDoc;
    using (Stream str = myDoc.MainDocumentPart.GetStream())
    using (XmlReader xr = XmlReader.Create(str))
        mainDocumentXDoc = XDocument.Load(xr);
    return mainDocumentXDoc;

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.