简体   繁体   English

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

[英]Export DocX file with Footer using DocumentFormat.OpenXml

I want to generate a DocX file with footer from HTML. 我想用HTML生成带有页脚的DocX文件。
Using the following lib: DocumentFormat.OpenXml 使用以下lib:DocumentFormat.OpenXml

I manage to generate the DocX file, BUT without Footer. 我设法生成DocX文件,但没有页脚。

The code that I use is the following: 我使用的代码如下:

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;
    }
}

I tried some other examples too for generating the footer, but the results were the same: generated but WITHOUT footer. 我也尝试了一些其他的例子来生成页脚,但结果是一样的:生成但没有页脚。
What could be the problem ? 可能是什么问题呢 ?

This is how you can add footer to a docx file: 这是您可以添加页脚到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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 使用DocumentFormat.OpenXml(C#)更新.docx文档中的目录 - Update TOC in .docx document using DocumentFormat.OpenXml (C#) 我将如何使用DocumentFormat.OpenXml从docx文件中提取数据-详情如下 - How will i extract the data from the docx file using DocumentFormat.OpenXml -details below 使用DocumentFormat.OpenXml dll读取.Doc文件 - Reading .Doc File using DocumentFormat.OpenXml dll 使用Documentformat.OpenXML在C#中验证Excel文件 - Validate Excel file in c# using Documentformat.OpenXML 无法加载文件或程序集 &#39;DocumentFormat.OpenXml - Could not load file or assembly 'DocumentFormat.OpenXml 使用DocumentFormat.OpenXml替换Word中的数据 - Replacing data in word using DocumentFormat.OpenXml 使用 openXML 将 docx/doc 第一个页眉和页脚导出为 docx 文件 - Export docx/doc First Header and Footer as docx File Using openXML Coldfusion OpenXml 错误:无法加载文件或程序集“DocumentFormat.OpenXml” - Coldfusion OpenXml Error: Could not load file or assembly 'DocumentFormat.OpenXml' 使用DocumentFormat.OpenXML创建的Excel文件(.xlsx)在Excel打开时需要修复 - Excel file (.xlsx) created by using DocumentFormat.OpenXML needs to be repaired when opening in Excel 如何使用DocumentFormat.OpenXml在Word模板中编辑书签并将其另存为新的PDF文件? - How to edit bookmarks in a Word template using DocumentFormat.OpenXml and save it as a new PDF file?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM