ar.gorgin
ar.gorgin

Reputation: 5022

How to insert HTML to Word?

I have a HtmlEditor for get text . (

Paragraph one.

Paragraph in a blockquote.

Paragraph two.

)

I want insert html to word . I use open xml but dont work .

void ConvertHTML(string htmlFileName, string docFileName)
{
    // Create a Wordprocessing document. 
    using (WordprocessingDocument package = WordprocessingDocument.Create(docFileName, WordprocessingDocumentType.Document))
    {
        // Add a new main document part. 
        package.AddMainDocumentPart();

        // Create the Document DOM. 
        package.MainDocumentPart.Document = new DocumentFormat.OpenXml.Wordprocessing.Document(new Body());
        Body body = package.MainDocumentPart.Document.Body;

        XPathDocument htmlDoc = new XPathDocument(htmlFileName);

        XPathNavigator navigator = htmlDoc.CreateNavigator();
        XmlNamespaceManager mngr = new XmlNamespaceManager(navigator.NameTable);
        mngr.AddNamespace("xhtml", "http://www.w3.org/1999/xhtml");

        XPathNodeIterator ni = navigator.Select("html");
        while (ni.MoveNext())
        {
            body.AppendChild<Paragraph>(new Paragraph(new Run(new  Text(ni.Current.Value))));
        }

        // Save changes to the main document part. 
        package.MainDocumentPart.Document.Save();
    }
}

EDIT

This link ,Link is very useful

Upvotes: 1

Views: 2533

Answers (1)

Basheer Jarrah
Basheer Jarrah

Reputation: 370

public static void ConvertHTML(string htmlFilePath, string wordFilePath)
{
    //Read HTML file content
    string HTML = File.ReadAllText(htmlFilePath);

    using WordprocessingDocument wordDocument = WordprocessingDocument.Create(wordFilePath, DocumentFormat.OpenXml.WordprocessingDocumentType.Document);

    // Add a new main document part. 
    MainDocumentPart mainPart = wordDocument.AddMainDocumentPart();
    
    mainPart.Document = new Document();
    Body body = new();
    mainPart.Document.Append(body);

    //Write HTML content
    Paragraph paragraph = new();
    Run run = new();
    run.Append(new Text(HTML));
    paragraph.Append(run);
    body.Append(paragraph);

    //Save the document
    mainPart.Document.Save();

}

Upvotes: 0

Related Questions