Joe W
Joe W

Reputation: 1890

Find the number of pages in a Word document Section using Interop

I'm trying to find the number of pages in a Section of a Word document using Interop in c#.

The main goal is really to find out if a header is visible or not. (E.g. a document is only 1 page, the DifferentFirstpageHeaderFooter is enabled, so the wdHeaderFooterPrimary exists but is technically not shown (because there's only 1 page and not 2 or more).) So if you can find a different way to figure out how to do this, I'm fine with that too.

Currently, WdInformation.wdActiveEndPageNumber works if there is only 1 section in the document, but if there is 2, and I'm doing the processing of the second section, wdActiveEndPageNumber gives me the total number of pages including section 1.

var section = headerFooter.Parent as Section;
int numOfPages = section.Range.Information[WdInformation.wdActiveEndPageNumber];

Upvotes: 2

Views: 4646

Answers (1)

user1379931
user1379931

Reputation:

I don't have the C# for this, but using VBA syntax what you need for "section n" is

a. if n = 1 then you look at

theDocument.sections[1].Range.Information[WdInformation.wdActiveEndPageNumber]

b. if n > 1 then you establish that section n exists, then look at

theDocument.sections[n].Range.Information[WdInformation.wdActiveEndPageNumber]-
theDocument.sections[n-1].Range.Information[WdInformation.wdActiveEndPageNumber]

and notice that case (b) can return 0 if you have a continuous section break on the last page of section n. I don't know what that would mean in terms of the headers that you would have, but I'd hope it would mean you just had the first page header.

Upvotes: 4

Related Questions