How to change Word document orientation?
Page setup belongs to a section, not to the document. doc.BodySection() returns
the section covering everything after the last section break, which on a document
with no breaks is the whole file.
package main
import (
"log"
"os"
"github.com/unidoc/unioffice/v2/common/license"
"github.com/unidoc/unioffice/v2/document"
"github.com/unidoc/unioffice/v2/measurement"
"github.com/unidoc/unioffice/v2/schema/soo/wml"
)
func init() {
if err := license.SetMeteredKey(os.Getenv(`UNIDOC_LICENSE_API_KEY`)); err != nil {
panic(err)
}
}
func main() {
doc := document.New()
defer doc.Close()
para := doc.AddParagraph()
para.SetStyle("Title")
para.AddRun().AddText("What is Lorem Ipsum?")
// A4 is 8.3 x 11.7 inches. Pass the portrait dimensions even for landscape.
section := doc.BodySection()
section.SetPageSizeAndOrientation(
measurement.Inch*8.3,
measurement.Inch*11.7,
wml.ST_PageOrientationLandscape,
)
if err := doc.SaveToFile("orientation.docx"); err != nil {
log.Fatalf("error saving document: %s", err)
}
}Pass portrait dimensions, always
This is the part that catches people. SetPageSizeAndOrientation transposes the
two dimensions itself when the orientation is landscape, writing the width from
the height argument and the height from the width one.
So you always give it the paper’s portrait measurements and let it do the swap.
Passing pre-swapped dimensions along with ST_PageOrientationLandscape produces
a page that is 11.7 inches wide and 8.3 tall, which is a tall page on wide paper,
and nothing reports an error either way. The godoc does not say which the caller
is expected to supply.
wml.ST_PageOrientationPortrait is the other value, and leaving the orientation
unset reads as portrait.
Different orientations in one document
Because the setting belongs to a section, a document with a single landscape page
in the middle needs more than one section. AddSection on a paragraph’s
properties starts a new one, and it comes back empty rather than inheriting from
the section before it, so set the page size and margins again on each.
The page layout guides cover sections, margins and columns in more detail.