使用DocumentFormat.OpenXml使用页脚导出DocX文件

时间:2019-05-20 13:17:12

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

我想从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;
    }
}

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

1 个答案:

答案 0 :(得分:0)

这是将页脚添加到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;
}