0

I have a template word file composed by 2 pages, each page has a bookmark, the first page bookmark name is A4 and the second page bookmark name is A3, but when I read all bookmarks from the word document I get them in alphabetical order, I want them in page order, how can i do this?

foreach (Bookmark bookMark in MergeResultDoc.Bookmarks) 
            {//IMPORTANTE:IL NOME DEL SEGNALIBRO DEVE ESSERE IL TIPO DI CARTA
                pagInizio = Convert.ToInt32(pagNum);
                pagNum = bookMark.Range.Information[WdInformation.wdActiveEndPageNumber].ToString();
                addData( pagInizio, pagNum, bookMark.Name);
                iteration++;
            }
Deduplicator
  • 44,692
  • 7
  • 66
  • 118
Daniele Sassoli
  • 899
  • 12
  • 34

3 Answers3

1

You can read the bookMark.Start value. This returns the start position of the Bookmark in the document. So you can run over all Bookmarks and sort them by their start position.

Here is a code to do that:

// List to store all bookmarks sorted by position.
List<Bookmark> bmList = new List<Bookmark>();

// Iterate over all the Bookmarks and add them to the list (unordered).
foreach (Bookmark curBookmark in MergeResultDoc.Bookmarks)
{
    bmList.Add(curBookmark);
}

// Sort the List by the Start member of each Bookmark.
// After this line the bmList will be ordered.
bmList.Sort(delegate(Bookmark bm1, Bookmark bm2)
{
    return bm1.Start.CompareTo(bm2.Start);
});
etaiso
  • 2,736
  • 3
  • 26
  • 38
  • Hy, thank's for your answer, is there some reason why I should prefer this one to gleng's one? – Daniele Sassoli Dec 12 '13 at 08:46
  • 1
    I'm not familiar with LINQ so I couldn't offer this but I think gleng's (with the correction of replacing `OrderBy` with `Cast`) is more clear and beautiful than mine (still, one line!). – etaiso Dec 12 '13 at 09:25
0

Use LINQ OrderBy:

var orderedResults = MergeResultDoc.Bookmarks.OrderBy(d => d.Start).ToList();
gleng
  • 6,185
  • 4
  • 21
  • 35
  • You need a `.Cast()`; Interop collections are not generic. – SLaks Dec 11 '13 at 17:15
  • thank's, I think this is better: var orderedResults = MergeResultDoc.Bookmarks.Cast().OrderBy(d => d.pageNum).ToList(); but I get the following error: 'Microsoft.Office.Interop.Word.Bookmark' does not contain a definition for 'pagNum', ideas? – Daniele Sassoli Dec 11 '13 at 17:19
  • same problem with no definition of pagNum! – Daniele Sassoli Dec 11 '13 at 17:27
  • @DenisBokor Doh! Use `Start` instead of `pageNum`. I've updated my answer. Let me know if that works for you. – gleng Dec 11 '13 at 19:45
0

Document.Boomarks should return the bookmarks in alpha sequence.

Document.Content.Bookmarks should return the bookmarks in the sequence they appear in the document. But VBA collection documentation does not typically guarantee a particular sequence for anything, it's safer to read the Start (as suggested by etaiso) and sort using that.