Search code examples
c#ms-wordopenxmldocxopenxml-sdk

OpenXml Word Footnotes


I'm trying to iterate through a Word document and extract the footnotes out of it, with a reference to where they belong in the paragraph.
I'm not sure how to do this.

I saw that in order to get all the footnotes I can do something like this:

FootnotesPart footnotesPart = doc.MainDocumentPart.FootnotesPart;
if (footnotesPart != null)
{
    IEnumerable<Footnote> footnotes = footnotesPart.Footnotes.Elements<Footnote>();

    foreach (var footnote in footnotes)
    {
         ...
    }
}

However, I don't know how to know where each footnote belongs in the paragraph.
I want, for instance, to take a footnote, and put it in brackets inside the text where it was a footnote before.
How do I do this?


Solution

  • You have to locate the FootnoteReference element with the same Id as the FootNote. This will give you the Run element, where the footnote is located.

    Sample code:

    FootnotesPart footnotesPart = doc.MainDocumentPart.FootnotesPart;
    if (footnotesPart != null)
    {
        var footnotes = footnotesPart.Footnotes.Elements<Footnote>();
        var references = doc.MainDocumentPart.Document.Body.Descendants<FootnoteReference>().ToArray();
        foreach (var footnote in footnotes)
        {
            long id = footnote.Id;
            var reference = references.Where(fr => (long)fr.Id == id).FirstOrDefault();
            if (reference != null)
            {
                Run run = reference.Parent as Run;
                reference.Remove();
                var fnText = string.Join("", footnote.Descendants<Run>().SelectMany(r => r.Elements<Text>()).Select(t => t.Text)).Trim();
                run.Parent.InsertAfter(new Run(new Text("(" + fnText + ")")), run);
            }
        }
    }
    doc.MainDocumentPart.Document.Save();
    doc.Close();