Skip to content

Page Count

The page count sits in a document’s extended app properties, written there by whatever editor last saved the file. AppProperties.Pages reads it back.

doc, err := document.Open("document.docx")
if err != nil {
    log.Fatalf("error opening document: %s", err)
}
defer doc.Close()

fmt.Println("Pages:", doc.AppProperties.Pages())

The value is an int32, and it is 0 when the property is absent.

It is metadata, not a measurement

UniOffice does not lay a document out into pages, so it has nothing to count. What Pages returns is what the producing application recorded at save time. Two consequences follow.

A document created with document.New() reports 0, however much content you add to it, because no editor has ever paginated it. That is stated in the godoc and is not a bug to work around.

A document opened, edited and saved with UniOffice keeps whatever count it arrived with. Delete half the content and the number does not change. AppProperties.SetPages will write a different value, but it writes whatever you pass without checking it, so it is a way to record a count you obtained elsewhere rather than a way to compute one.

Getting a real count

What you needHow to get it
A number shown inside the documentA NUMPAGES field; see Page numbers.
A number in your Go programConvert to PDF and count the pages of the result.
A number from a file Word wroteAppProperties.Pages, which is what this page covers.

The field approach hands the problem to Word or LibreOffice, which do paginate. The PDF approach gives your program a number, at the cost of running the conversion; see Convert a document to PDF.

Run the example

The example opens the document.docx fixture in its own directory and prints its page count, then prints the count of a freshly created document to show the difference.

git clone https://github.com/unidoc/unioffice-examples.git
cd unioffice-examples/document/number-of-pages
go run main.go

If this is your first time using UniOffice, follow the getting started guide to create an API key and set up your development environment.

View the full source
Last updated on