如何通过 OpenXML 为 Header 设置 "Link To Previous" 设置

How to set the "Link To Previous" Setting for a Header via OpenXML

我使用 Telerik 报告生成器创建了一个 Word docx 文件。每个页面都包含一个 header。当我打开 docx 时,最初看起来不错...

现在所有页面上的 header 都可以正确输出,但是,如果我对 header 进行更改,则更改是未反映在所有后续 header 中。事实证明这是因为 header 不是 "linked to the previous" header。此屏幕截图显示工具栏按钮 "Link to Previous" 已启用,加上 header 本身的 "Same as Previous" 装饰表明此 header 将与第一个 [=] 共享完全相同的内容34=]。

现在我想弄清楚如何通过 OpenXML 以编程方式设置它。这让我想到了一些类似的代码示例,例如 Replace the header in a word processing document (Open XML SDK)。据我所知,方法是找到第一个 header 的 ID,然后在文档的所有部分中,删除现有的 header 并将其替换为对第一个的引用header。

我想到了这个:

private void FixDocument(string outputFile)
{
    using (var wdDoc = WordprocessingDocument.Open(outputFile, true))
    {
        MainDocumentPart mainPart = wdDoc.MainDocumentPart;
        var firstHeader = mainPart.HeaderParts.FirstOrDefault();
        var firstHeaderId = mainPart.GetIdOfPart(firstHeader);

        // Get SectionProperties and Replace HeaderReference and FooterRefernce with new Id

        var sections = mainPart.Document.Descendants<SectionProperties>();    
        foreach (var section in sections)
        {
            // Delete existing references to headers and footers
            section.RemoveAllChildren<HeaderReference>();
            // Create the new header and footer reference node
            section.PrependChild<HeaderReference>(new HeaderReference() { Id = firstHeaderId, Type = HeaderFooterValues.Default });
        }              
    }
}

保存文档并打开后,似乎 a) 原来的 header 还在,其中 none 链接到第一个。

我不确定哪里出错了 - 任何帮助将不胜感激。

如果文档的第一部分有所需的页眉 and/or 页脚,那么我认为为了在您只需要删除其他部分中指定的任何页眉 and/or 页脚即可。

换句话说,试试这个:

private void FixDocument(string outputFile)
{
    using (var wdDoc = WordprocessingDocument.Open(outputFile, true))
    {
        var mainPart = wdDoc.MainDocumentPart;
        var sections = mainPart.Document.Descendants<SectionProperties>().Skip(1);

        foreach (var section in sections)
        {
            section.RemoveAllChildren<HeaderReference>();
        }
    }
}