简体   繁体   中英

add html content in existing docx file using openxml in C#

How do I add/append HTML content in an existing .docx file, using OpenXML in asp.net C#?

In an existing word file, I want to append the html content part. For example:

In this example, I want to place "This is a Heading" inside a H1 tag.

Here its my code

protected void Button1_Click(object sender, EventArgs e)
    {

        try
        {
            using (WordprocessingDocument doc = WordprocessingDocument.Open(@"C:\Users\admin\Downloads\WordGenerator\WordGenerator\FTANJS.docx", true))
            {
                string altChunkId = "myId";
                MainDocumentPart mainDocPart = doc.MainDocumentPart;

                var run = new Run(new Text("test"));
                var p = new Paragraph(new ParagraphProperties(new Justification() { Val = JustificationValues.Center }), run);

                var body = mainDocPart.Document.Body;
                body.Append(p);


                MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes("<html><head></head><body><h1>HELLO</h1></body></html>"));

                // Uncomment the following line to create an invalid word document.
                // MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes("<h1>HELLO</h1>"));

                // Create alternative format import part.
                AlternativeFormatImportPart formatImportPart =
                   mainDocPart.AddAlternativeFormatImportPart(
                      AlternativeFormatImportPartType.Html, altChunkId);
                //ms.Seek(0, SeekOrigin.Begin);

                // Feed HTML data into format import part (chunk).
                formatImportPart.FeedData(ms);
                AltChunk altChunk = new AltChunk();
                altChunk.Id = altChunkId;

                mainDocPart.Document.Body.Append(altChunk);
            }
        }
        catch (Exception ex)
        {

            ex.ToString ();
        }


    }

The short answer is "You can't add HTML to a docx file".

Docx is an open format defined here . If you're using the Microsoft version they have a number of extensions.

In any case, the file contains XML, not HTML and you can't simply add HTML to a docx file. There are styles and formatting objects and pointers that all need to be updated.

If you need to modify a docx file and don't want to do a lot of research and a lot of coding, you'll need to find an existing library to work with.

Add HTML content as Chunk should work, and you are almost there.

If I understand the question properly, this code should work.

        //insert html content to H1 tag
        using(WordprocessingDocument fDocx = WordprocessingDocument.Open(sDocxFile,true))
        {
            string sChunkID = "myhtmlID";
            AlternativeFormatImportPart oChunk = fDocx.MainDocumentPart.AddAlternativeFormatImportPart(AlternativeFormatImportPartType.Html, sChunkID);
            using(FileStream fs = File.Open(sHtml,FileMode.OpenOrCreate))
            {
                oChunk.FeedData(fs);
            }
            AltChunk oAltChunk = new AltChunk();
            oAltChunk.Id =sChunkID ;

            //insert html to the tag of 'H1' and remove H1.
            Body body = fDocx.MainDocumentPart.Document.Body;
            Paragraph theParagraph = body.Descendants<Paragraph>().Where(p => p.InnerText == "H1").FirstOrDefault();
            theParagraph.InsertAfterSelf<AltChunk>(oAltChunk);
            theParagraph.Remove();

            fDocx.MainDocumentPart.Document.Save();
        }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM