Search code examples
c#novacode-docx

How can I insert a cross-reference page number in Novacode DocX


I am creating a Word document using Novacode DocX in which I want to insert a piece of text, and then later on in the document insert a reference to it in the form of '(see page X)' where X is dynamically generated by Word.

In Word itself, I can easily do this by creating a bookmark for the first piece of text and inserting a cross-reference where I want the page number.

I think I know how to add a bookmark using DocX, but how do I create the cross-reference? Is this even possible in DocX?

Many thanks in advance for your help, Chris


Solution

  • After some fiddling, I finally found a way to achieve this:

    internal void AddCrossReference(DocX doc, Paragraph p, string destination)
            {
                XNamespace ns= doc.Xml.Name.NamespaceName;
                XNamespace xmlSpace = doc.Xml.GetNamespaceOfPrefix("xml");
                p = p.Append(" (see pp");
                p.Xml.Add(new XElement(ns + "r", new XElement(ns + "fldChar", new XAttribute(ns + "fldCharType", "begin"))));
                p.Xml.Add(new XElement(ns + "r", new XElement(ns + "instrText", new XAttribute(xmlSpace + "space", "preserve"), String.Format(" PAGEREF {0} \\h ", destination))));
                p.Xml.Add(new XElement(ns + "r", new XElement(ns + "fldChar", new XAttribute(ns + "fldCharType", "separate"))));
                p.Xml.Add(new XElement(ns + "r", new XElement(ns + "rPr", new XElement(ns + "noProof")), new XElement(ns + "t", "1")));
                p.Xml.Add(new XElement(ns + "r", new XElement(ns + "fldChar", new XAttribute(ns + "fldCharType", "end"))));
                p = p.Append(")");
            }
    

    destination is the name of the bookmark you want to cross-reference.

    Any suggested improvements would be most welcome.