Renumber footnotes with c#/openxml

691 views Asked by At

My program should renumber footnotes in a word file.

We have a VBA-Macro, that does the same but it´s too slow.

    Dim fussnote As Footnote
    For Each fussnote In ActiveDocument.Footnotes
    fussnote.Reference.Select
    With Selection
       With .FootnoteOptions
            .Location = wdBottomOfPage
            .NumberingRule = wdRestartContinuous
            .StartingNumber = 1
            .NumberStyle = wdNoteNumberStyleArabic
            .NumberingRule = wdRestartSection
       End With
       .Footnotes.Add range:=Selection.range, Reference:=""
    End With
Next

I tried to clone all footnotes, then go through them (and their references) and change their ID (is Id the right property?)

My Code looks like this (not working):

        public override void Work(WordprocessingDocument args)
    {
        var __allFootnotes = (Footnotes)args.MainDocumentPart
            .FootnotesPart.Footnotes.Clone();
        var footnotes = __allFootnotes.Elements<Footnote>()
            .SkipWhile(f => !(f.Id.Value > 0)).ToList();
        RenumberFootnotes(footnotes, 
            args.MainDocumentPart.Document.Body.Descendants<Paragraph>().ToList());

        var __styles = args.MainDocumentPart
            .StyleDefinitionsPart.Styles;

        for (int i = 0; i < footnotes.Count(); i++)
        {
            //var footnote = footnotes[i];
        }

        args.MainDocumentPart.FootnotesPart
            .Footnotes = __allFootnotes;
    }


    private void RenumberFootnotes(List<Footnote> footnotes, List<Paragraph> paragraphs)
    {
        var __p = paragraphs.Where(p => p.Descendants<FootnoteReference>().Any());
        var __references = __p.SelectMany(p => p.Descendants<FootnoteReference>());
        for (int i = 1; i < footnotes.Count; i++)
        {
            var __tempId = footnotes[i].Id.Value;
            footnotes[i].Id.Value = i;
            var __reference = __references.First(fr => fr.Id.Value == __tempId);
            __reference.Id.Value = i;
        }
    }
1

There are 1 answers

0
Deduplicator On

Solution extracted from question:

You have to add a new 'FootnoteReferenceMark' Object into a Run in your Footnote. 'footnote' is my variable for a footnote. Then i just take the first descendant of type 'Run' and append a new child of 'FootnoteReferenceMark'.

footnote.Descendants<Run>().First().AppendChild(new FootnoteReferenceMark());