【问题标题】:Export DocX file with Footer using DocumentFormat.OpenXml使用 DocumentFormat.OpenXml 导出带页脚的 DocX 文件
【发布时间】:2019-05-22 00:13:35
【问题描述】:

我想从 HTML 生成一个带有页脚的 DocX 文件。
使用以下库:DocumentFormat.OpenXml

我设法生成了 DocX 文件,但没有页脚。

我使用的代码如下:

class HtmlToDoc
{
    public static byte[] GenerateDocX(string html)
    {
        MemoryStream ms;
        MainDocumentPart mainPart;
        Body b;
        Document d;
        AlternativeFormatImportPart chunk;
        AltChunk altChunk;

        string altChunkID = "AltChunkId1";

        ms = new MemoryStream();

        using(var myDoc = WordprocessingDocument.Create(ms, WordprocessingDocumentType.Document))
        {
            mainPart = myDoc.MainDocumentPart;

            if (mainPart == null)
            {
                mainPart = myDoc.AddMainDocumentPart();
                b = new Body();
                d = new Document(b);
                d.Save(mainPart);
            }

            chunk = mainPart.AddAlternativeFormatImportPart(AlternativeFormatImportPartType.Xhtml, altChunkID);

            using (Stream chunkStream = chunk.GetStream(FileMode.Create, FileAccess.Write))
            {
                using (StreamWriter stringStream = new StreamWriter(chunkStream))
                {
                    stringStream.Write("<html><head></head><body>" + html + "</body></html>");
                }
            }

            altChunk = new AltChunk();
            altChunk.Id = altChunkID;
            mainPart.Document.Body.InsertAt(altChunk, 0);

            AddFooter(myDoc);
            mainPart.Document.Save();
        }

        return ms.ToArray();
    }

    private static void AddFooter(WordprocessingDocument doc)
    {
        string newFooterText = "New footer via Open XML Format SDK 2.0 classes";

        MainDocumentPart mainDocPart = doc.MainDocumentPart;

        FooterPart newFooterPart = mainDocPart.AddNewPart<FooterPart>();
        string rId = mainDocPart.GetIdOfPart(newFooterPart);

        GeneratePageFooterPart(newFooterText).Save(newFooterPart);

        foreach (SectionProperties sectProperties in
          mainDocPart.Document.Descendants<SectionProperties>())
        {
            foreach (FooterReference footerReference in
              sectProperties.Descendants<FooterReference>())
                sectProperties.RemoveChild(footerReference);

            FooterReference newFooterReference =
              new FooterReference() { Id = rId, Type = HeaderFooterValues.Default };
            sectProperties.Append(newFooterReference);
        }

        mainDocPart.Document.Save();
    }


    private static Footer GeneratePageFooterPart(string FooterText)
    {
        PositionalTab pTab = new PositionalTab()
        {
            Alignment = AbsolutePositionTabAlignmentValues.Center,
            RelativeTo = AbsolutePositionTabPositioningBaseValues.Margin,
            Leader = AbsolutePositionTabLeaderCharValues.None
        };

        var elment =
            new Footer(
                new Paragraph(
                    new ParagraphProperties(
                        new ParagraphStyleId() { Val = "Footer" }),
                    new Run(pTab,
                        new Text(FooterText))
                            )
                        );
        return elment;
    }
}

我也尝试了一些其他示例来生成页脚,但结果相同:生成但没有页脚。
可能是什么问题呢 ?

【问题讨论】:

    标签: c# .net winforms openxml openxml-sdk


    【解决方案1】:

    这是您可以将页脚添加到 docx 文件的方法:

    static void Main(string[] args)
    {
        using (WordprocessingDocument document = 
            WordprocessingDocument.Open("Document.docx", true))
        {
            MainDocumentPart mainDocumentPart = document.MainDocumentPart;
    
            // Delete the existing footer parts
            mainDocumentPart.DeleteParts(mainDocumentPart.FooterParts);
    
            // Create a new footer part
            FooterPart footerPart = mainDocumentPart.AddNewPart<FooterPart>();
    
            // Get Id of footer part
            string footerPartId = mainDocumentPart.GetIdOfPart(footerPart);
    
            GenerateFooterPartContent(footerPart);
    
            // Get SectionProperties and Replace FooterReference with new Id
            IEnumerable<SectionProperties> sections = 
                mainDocumentPart.Document.Body.Elements<SectionProperties>();
    
            foreach (var section in sections)
            {
                // Delete existing references to headers and footers
                section.RemoveAllChildren<FooterReference>();
    
                // Create the new header and footer reference node
                section.PrependChild<FooterReference>(
                    new FooterReference() { Id = footerPartId });
            }
        }
    }
    
    static void GenerateFooterPartContent(FooterPart part)
    {
        Footer footer1 = new Footer();
        Paragraph paragraph1 = new Paragraph();
        ParagraphProperties paragraphProperties1 = new ParagraphProperties();
        ParagraphStyleId paragraphStyleId1 = new ParagraphStyleId() { Val = "Footer" };
    
        paragraphProperties1.Append(paragraphStyleId1);
    
        Run run1 = new Run();
        Text text1 = new Text();
        text1.Text = "Footer";
    
        run1.Append(text1);
    
        paragraph1.Append(paragraphProperties1);
        paragraph1.Append(run1);
        footer1.Append(paragraph1);
        part.Footer = footer1;
    }
    

    【讨论】:

      猜你喜欢
      • 2018-03-18
      • 1970-01-01
      • 2012-01-24
      • 1970-01-01
      • 2016-07-25
      • 2018-04-05
      • 1970-01-01
      • 2015-11-16
      • 2015-12-14
      相关资源
      最近更新 更多