首页 > 解决方案 > 如何从 html 字符串创建单词标题

问题描述

我正在从一个 html 字符串生成一个 word docx 文件,并使用我发现的各种文章来向该文档添加简单的页眉和页脚。我现在需要做的是也从 html 字符串生成标题,但我正在努力寻找如何完成此操作的示例。这个问题的作者: Export docx/doc First Header and Footer as docx File Using openXML 说他已经做到了,但不幸的是他没有发布一个例子。

我下面的代码成功添加了一个标题,但正如您从代码中看到的那样,它只会将 html 作为文本添加到标题中,而我想传入一个 html 字符串并将其作为格式化的 html 出现在标题中。

有人做过吗?

static void AddHeaderPart(MainDocumentPart mainPart, string headerHtml, Encoding encoding)
        {
            if (mainPart == null || string.IsNullOrEmpty(headerHtml))
            {return;}

            // Create a new header part.
            HeaderPart headerPart = mainPart.AddNewPart<HeaderPart>();

            // Get Id of the headerPart.
            string rId = mainPart.GetIdOfPart(headerPart);


            // Call GenerateHeaderPartContent
            GenerateHeaderPartContent(mainPart, headerPart, headerHtml, encoding);

            // Get SectionProperties and Replace HeaderReference with new Id.
            IEnumerable<SectionProperties> sectPrs = mainPart.Document.Body.Elements<SectionProperties>();
            foreach (var sectPr in sectPrs)
            {
                // Delete existing references to headers.
                sectPr.RemoveAllChildren<HeaderReference>();

                // Create the new header reference node.
                sectPr.PrependChild<HeaderReference>(new HeaderReference() { Id = rId, Type = HeaderFooterValues.Default });
            }

        }

static void GenerateHeaderPartContent(MainDocumentPart mainPart, HeaderPart headerPart, string headerHtml, Encoding encoding)
        {
            Header header1 = new Header() { MCAttributes = new MarkupCompatibilityAttributes() { Ignorable = "w14 wp14" } };
            header1.AddNamespaceDeclaration("wpc", "http://schemas.microsoft.com/office/word/2010/wordprocessingCanvas");
            header1.AddNamespaceDeclaration("mc", "http://schemas.openxmlformats.org/markup-compatibility/2006");
            header1.AddNamespaceDeclaration("o", "urn:schemas-microsoft-com:office:office");
            header1.AddNamespaceDeclaration("r", "http://schemas.openxmlformats.org/officeDocument/2006/relationships");
            header1.AddNamespaceDeclaration("m", "http://schemas.openxmlformats.org/officeDocument/2006/math");
            header1.AddNamespaceDeclaration("v", "urn:schemas-microsoft-com:vml");
            header1.AddNamespaceDeclaration("wp14", "http://schemas.microsoft.com/office/word/2010/wordprocessingDrawing");
            header1.AddNamespaceDeclaration("wp", "http://schemas.openxmlformats.org/drawingml/2006/wordprocessingDrawing");
            header1.AddNamespaceDeclaration("w10", "urn:schemas-microsoft-com:office:word");
            header1.AddNamespaceDeclaration("w", "http://schemas.openxmlformats.org/wordprocessingml/2006/main");
            header1.AddNamespaceDeclaration("w14", "http://schemas.microsoft.com/office/word/2010/wordml");
            header1.AddNamespaceDeclaration("wpg", "http://schemas.microsoft.com/office/word/2010/wordprocessingGroup");
            header1.AddNamespaceDeclaration("wpi", "http://schemas.microsoft.com/office/word/2010/wordprocessingInk");
            header1.AddNamespaceDeclaration("wne", "http://schemas.microsoft.com/office/word/2006/wordml");
            header1.AddNamespaceDeclaration("wps", "http://schemas.microsoft.com/office/word/2010/wordprocessingShape");

            Paragraph paragraph1 = new Paragraph();

            ParagraphProperties paragraphProperties1 = new ParagraphProperties();
            ParagraphStyleId paragraphStyleId1 = new ParagraphStyleId() { Val = "Header" };

            paragraphProperties1.Append(paragraphStyleId1);

            //This adds the headerHtml as text - how to add it as html?
            Run run1 = new Run();
            Text text1 = new Text();
            text1.Text = headerHtml;

            run1.Append(text1);

            paragraph1.Append(paragraphProperties1);
            paragraph1.Append(run1);

            header1.Append(paragraph1);

            headerPart.Header = header1;
        }

标签: c#htmlms-wordopenxml-sdk

解决方案


因此,下面的代码使用 altChunk 将 html 添加到标题中。它并不完美,因为当我使用 OpenXmlValidator 验证生成的文档时出现验证错误,尽管文档仍然可以在 word 中打开,但我将其发布在这里作为答案,因为它确实执行了我上面的要求并且它可能会帮助其他人:

static void GenerateHeaderPartContent(MainDocumentPart mainPart, HeaderPart headerPart, string headerHtml)
        {
            Header header1 = new Header() { MCAttributes = new MarkupCompatibilityAttributes() { Ignorable = "w14 wp14" } };
            header1.AddNamespaceDeclaration("wpc", "http://schemas.microsoft.com/office/word/2010/wordprocessingCanvas");
            header1.AddNamespaceDeclaration("mc", "http://schemas.openxmlformats.org/markup-compatibility/2006");
            header1.AddNamespaceDeclaration("o", "urn:schemas-microsoft-com:office:office");
            header1.AddNamespaceDeclaration("r", "http://schemas.openxmlformats.org/officeDocument/2006/relationships");
            header1.AddNamespaceDeclaration("m", "http://schemas.openxmlformats.org/officeDocument/2006/math");
            header1.AddNamespaceDeclaration("v", "urn:schemas-microsoft-com:vml");
            header1.AddNamespaceDeclaration("wp14", "http://schemas.microsoft.com/office/word/2010/wordprocessingDrawing");
            header1.AddNamespaceDeclaration("wp", "http://schemas.openxmlformats.org/drawingml/2006/wordprocessingDrawing");
            header1.AddNamespaceDeclaration("w10", "urn:schemas-microsoft-com:office:word");
            header1.AddNamespaceDeclaration("w", "http://schemas.openxmlformats.org/wordprocessingml/2006/main");
            header1.AddNamespaceDeclaration("w14", "http://schemas.microsoft.com/office/word/2010/wordml");
            header1.AddNamespaceDeclaration("wpg", "http://schemas.microsoft.com/office/word/2010/wordprocessingGroup");
            header1.AddNamespaceDeclaration("wpi", "http://schemas.microsoft.com/office/word/2010/wordprocessingInk");
            header1.AddNamespaceDeclaration("wne", "http://schemas.microsoft.com/office/word/2006/wordml");
            header1.AddNamespaceDeclaration("wps", "http://schemas.microsoft.com/office/word/2010/wordprocessingShape");

            Paragraph paragraph1 = new Paragraph();
            ParagraphProperties paragraphProperties1 = new ParagraphProperties();
            ParagraphStyleId paragraphStyleId1 = new ParagraphStyleId() { Val = "Header" };

            paragraphProperties1.Append(paragraphStyleId1);
            paragraph1.Append(paragraphProperties1);

            string altChunkId = "AltChunkId1";
            AlternativeFormatImportPart chunk = headerPart.AddAlternativeFormatImportPart(
                AlternativeFormatImportPartType.Html, altChunkId);

            // Note that headerHtml should be full html, not just a snippet
            // eg. <html><h1>My Header</h1></html> is OK
            // <h1>My Header</h1> is not OK
            MemoryStream ms = new MemoryStream(new UTF8Encoding(true).GetPreamble().Concat(Encoding.UTF8.GetBytes(headerHtml)).ToArray());

            chunk.FeedData(ms);

            AltChunk altChunk = new AltChunk();
            altChunk.Id = altChunkId;

            Run run1 = new Run();
            RunProperties runProps = new RunProperties();
            NoProof noProof1 = new NoProof();
            runProps.Append(noProof1);

            run1.Append(runProps);
            run1.Append(altChunk);

            paragraph1.Append(run1);
            header1.Append(paragraph1);

            headerPart.Header = header1;
        }

推荐阅读