Adding content to a slide

Add text, shapes, images, tables, and charts to a slide, and connect them with lines.

Most content sets its position and size in its own Geometry. Wrap the content in a CanvasObject, which has one field for each kind of content, such as textbox or shape. The CanvasObject goes inside a SlideObject in the slide’s contents.

The text example shows how to wrap content in a CanvasObject and a SlideObject. The examples after it build only the object.

Set one case of a union

CanvasObject, Fill, Color, Stroke, Path, and other unions hold one of several kinds of value, called cases. Each case is an optional field. Set the one field for the case you want. Two examples below each set one case: CanvasObject(textbox=...) in the text example and Path(bezier=...) in the shape example.

The following example builds a solid fill and a stroke with no line:

from creator_studio_doc_format.core import RGBA, Color, Fill, Stroke

# `Fill.color` holds a `Color`, which is itself a union.
red = Fill(color=Color(rgba=RGBA(red=0.8, green=0.1, blue=0.1, alpha=1)))
no_border = Stroke(empty=True)  # A case with no payload takes `True`.

A union with no case set raises pydantic.ValidationError. However, a union with two cases set raises nothing, and an app that opens the document uses only one of them. TaggedUnionModel describes the full contract, and Recognize values that take one of several forms shows how a document writes a union.

Add text

The text field of a Textbox or a Shape holds a Text, which holds one of three cases:

string

Plain text.

text_runs

A list of TextRun, for text with a style that changes within a line.

paragraphs

A list of Paragraph, for several lines, alignment, or a list.

Use the simplest case that holds your text:

from creator_studio_doc_format.core import (
    CanvasObject,
    CharacterProperties,
    Constituent,
    Paragraph,
    Slide,
    SlideObject,
    Text,
    Textbox,
    TextRun,
)

plain = Text(string="Stargazing Tips")
styled = Text(
    text_runs=[
        TextRun(string="Full moon", style=CharacterProperties(bold=True))
    ]
)
lines = Text(
    paragraphs=[
        Paragraph(contents=[Constituent(run=TextRun(string="First line"))]),
        Paragraph(contents=[Constituent(run=TextRun(string="Second line"))]),
    ]
)

# A content object goes on a slide inside a `SlideObject` and a `CanvasObject`.
slide = Slide(
    contents=[SlideObject(object=CanvasObject(textbox=Textbox(text=plain)))]
)

Add a shape

A shape’s outline is Shape.path, which holds a Path. The bezier case of a Path holds SVG path data. BezierPath.space sets the path’s coordinate space, which Keynote stretches over the shape’s geometry. To move, resize, or rotate a shape, change geometry rather than the path.

The simplest space is a unit box, where the path’s numbers are fractions of the shape:

from creator_studio_doc_format.core import (
    BezierPath,
    Geometry,
    Path,
    Position,
    Rect,
    Shape,
    Size,
)

UNIT_BOX = Rect(position=Position(x=0, y=0), size=Size(width=1, height=1))
OVAL = "M 0,0.5 A 0.5,0.5 0 1 1 1,0.5 A 0.5,0.5 0 1 1 0,0.5 Z"

shape = Shape(
    identifier="oval",
    geometry=Geometry(
        position=Position(x=1000, y=200), size=Size(width=180, height=180)
    ),
    path=Path(bezier=BezierPath(path=OVAL, space=UNIT_BOX)),
)

Add an image

An Image refers to its bytes through a Resource. Most images use an IndirectResource, which names a file in doc.resources. That store works like a dictionary of filenames to bytes:

import pathlib

from creator_studio_doc_format.core import (
    Image,
    IndirectResource,
    KeyxDocument,
    Resource,
)

doc = KeyxDocument.open("presentation.keyx")
png_bytes = pathlib.Path("cover.png").read_bytes()

name = doc.resources.unique_filename("cover.png")
doc.resources[name] = png_bytes
image = Image(
    resource=Resource(
        indirect=IndirectResource(identifier=name, filename="cover.png")
    ),
    geometry=Geometry(
        position=Position(x=160, y=120), size=Size(width=600, height=396)
    ),
)

unique_filename returns a name no file in the document uses yet, such as "cover 2.png" when the document already has a cover.png. identifier names the file that holds the bytes, and filename is the name Keynote shows. Without identifier, filename names the file too. A Movie or Audio object refers to its file the same way.

Add a table

A Table states its size in number_of_rows and number_of_columns. The counts must match the rows in content and the entries in column_headers. Every row also needs one cell for each column header. Adding a Row doesn’t update number_of_rows.

Important

value is the cell’s formatted display string. A number, date, or Boolean cell needs a typed unformatted_value. Without one, Keynote treats the cell as text. A text cell can omit it.

The following example builds a table of two rows and two columns:

from creator_studio_doc_format.core import (
    Cell,
    ColumnHeader,
    Row,
    Table,
    UnformattedValue,
)


def revenue_cell(millions: int) -> Cell:
    return Cell(
        value=str(millions),
        unformatted_value=UnformattedValue(number=millions),
    )


table = Table(
    geometry=Geometry(
        position=Position(x=160, y=260), size=Size(width=800, height=160)
    ),
    number_of_rows=2,
    number_of_columns=2,
    column_headers=[
        ColumnHeader(column_identifier="product"),
        ColumnHeader(column_identifier="revenue"),
    ],
    content=[
        Row(
            row_identifier="coffee",
            cells=[Cell(value="Coffee"), revenue_cell(41)],
        ),
        Row(
            row_identifier="tea",
            cells=[Cell(value="Tea"), revenue_cell(12)],
        ),
    ],
)

Add a chart

Keynote offers more than 20 kinds of charts. All of them take their data in the same grid, a ChartData. Its plot_direction sets whether the grid’s rows or its columns become the series:

from creator_studio_doc_format.core import (
    Chart,
    ChartData,
    ChartDataRow,
    ChartDataSource,
    ChartDataValue,
    ColumnChart,
    PlotDirection,
)

revenue = ChartData(
    chart_data_source=ChartDataSource.CHART_DATA_GRID,
    plot_direction=PlotDirection.ROWS_AS_SERIES,
    row_labels=["Coffee", "Tea"],
    column_labels=["Q1", "Q2", "Q3"],
    rows=[
        ChartDataRow(
            values=[ChartDataValue(number=n) for n in (42.1, 48.3, 51.0)]
        ),
        ChartDataRow(
            values=[ChartDataValue(number=n) for n in (38.5, 41.0, 44.2)]
        ),
    ],
)
chart = Chart(
    column=ColumnChart(
        data=revenue,
        geometry=Geometry(
            position=Position(x=160, y=200), size=Size(width=1200, height=700)
        ),
    )
)

Add a connection line

A ConnectionLine takes its position from its two ends, each an End. An end attaches to an object through its anchor, which names the object by Anchor.object_id. The object must be in the same list of objects as the line, such as the slide’s contents.

Wrap a line as CanvasObject(connectionLine=...). connectionLine and genericCanvasObject are the two camelCase fields of CanvasObject. The rest are lowercase.

Warning

Every end needs an end_point, even one that anchor attaches. Omitting it drops the whole line. For an attached end, use the object’s center.

An end with no anchor stays at its end_point. The following example attaches the arrow’s head to the oval from the shape example and leaves its tail unattached:

from creator_studio_doc_format.core import Anchor, ConnectionLine, End, LineEnd

arrow = ConnectionLine(
    tail=End(end_point=Position(x=450, y=290)),
    head=End(
        end_point=Position(x=1090, y=290),
        anchor=Anchor(object_id="oval"),
        line_end=LineEnd.FILLED_ARROW,
    ),
)

Style content with a preset

A preset lets content share one set of properties, which keeps styling consistent and the document compact.

The following example defines a body preset and a title preset that builds on it, then applies each to a run of text:

from creator_studio_doc_format.core import Preset

doc = KeyxDocument.open("presentation.keyx")
doc.presets.extend(
    [
        Preset("body", {"font_name": "Helvetica Neue", "font_size": 24}),
        # The title inherits `font_name` from the body.
        Preset(
            "title", {"font_size": 48, "bold": True}, parent_identifier="body"
        ),
    ]
)

# A model instance adopts a preset through `preset_identifier`.
heading = TextRun(
    string="Baking Sourdough",
    style=CharacterProperties(preset_identifier="title"),
)
step = TextRun(
    string="Feed the starter",
    style=CharacterProperties(preset_identifier="body"),
)

See also

  • Slide content, the API reference’s page for each kind of content

  • Resource store, which holds the bytes an image refers to

  • creator_studio_doc_format/examples/, a runnable script for each kind of slide content