How do I get the page width and height programmatically in Python?

I have the current document instance. I saw the pageproperties service but I haven’t been able to reference that service.

I tried

context.ServiceManager.createInstanceWithContext("com.sun.star.style.PageProperties", doc)

But it returns None.

Also tried

styles = model.getStyleFamilies()

I can get getStyleFamilies["ParagraphStyles"] but not PageProperties.

I would like to get the width and height of the page from writer, draw and any other documents if possible.

Also I would like to know the type of measure that is returned.

Any help is much appreciated to get to this one in Python.

Can you get PageStyles?

1 Like
import uno
from com.sun.star.awt.MessageBoxType import INFOBOX
from com.sun.star.awt.MessageBoxButtons import BUTTONS_OK

def page_size():
    doc = XSCRIPTCONTEXT.getDocument()
    page_styles = doc.getStyleFamilies().getByName("PageStyles")

    style_names = page_styles.getElementNames()
    if len(style_names) == 0:
        raise Exception("No page styles found in the document.")

    first_style_name = style_names[0]
    default_style = page_styles.getByName(first_style_name)

    width = default_style.Width
    height = default_style.Height
    width_mm = width / 100
    height_mm = height / 100

    toolkit = doc.CurrentController.Frame.ContainerWindow.getToolkit()
    parent = doc.CurrentController.Frame.ContainerWindow
    title = "Page Size Info"
    message = f"Using page style: {first_style_name}\nWidth: {width_mm} mm\nHeight: {height_mm} mm"

    box = toolkit.createMessageBox(parent, INFOBOX, BUTTONS_OK, title, message)
    box.execute()

g_exportedScripts = (page_size,)

This solution is perfect, I understand that the units are always milimeters, both questions solved. Thank you @flywire.

In the case of Impress and Draw, there was no PageStyles, and doc.getStyleFamilies().getElementNames() report:

('graphics', 'cell', 'table', 'Default')

And neither default, graphics, cell nor table have Width, nor Height. what would be the path to get the width and height of the page? I saw there is no record macro in those document types.

#case impress
doc = XSCRIPTCONTEXT.getDocument()
page = doc.DrawPages[0]
print( f"{page.Width = }\n{page.Height = }")
2 Likes

You can use one of the excellent object inspection tools Xray and MRI.
They can list all of the existing properties and methods (and others) of the programming objects.

Here is my tryings by usage of the XrayTool:

DrawPageStyle.odg (11.4 KB)

1 Like

That one is great for impress and draw, thank you @karolus . That was the missing piece.