Home/ Reference/ Recipes

Set font, read back, then fall back

See the code below. This is the most valuable pattern in the entire script: any property that can fail silently (font names, graphic styles) should be written, read

Scenario

Set font, read back, then fall back

Notes

See the code below. This is the most valuable pattern in the entire script: any property that can fail silently (font names, graphic styles) should be written, read back and rolled back this way.

Python example (runnable)

Requires pywin32. The example assumes app / doc / page / layer are already connected. See Connection & Init
Python
import time

def set_font(shape, font_name, size_pt=None,
             fallback="Source Han Sans Bold", tries=3):
    """
    Set the font on a text shape, then read it back to verify
    shape     : a text shape
    font_name : target font name, for example "Source Han Sans Bold"
    size_pt   : size in points, None leaves it untouched
    fallback  : font to fall back to when the first one will not take
    tries     : retries per font
    returns   : the font name that actually took, None if all failed
    """
    for name in [font_name] + ([fallback] if fallback else []):
        for _ in range(tries):
            try:
                ca = shape.Text.Story.Characters.All
                ca.Font = name
                if size_pt is not None:
                    ca.Size = size_pt
                time.sleep(0.3)                 # give the font time to actually apply
                if ca.Font == name:             # read back to verify
                    return name
            except Exception:
                break
    return None

shape = app.ActiveSelectionRange(1)
used = set_font(shape, "Source Han Sans Bold", 36)
print("Font actually applied: ", used or "All failed, nothing changed")

About this section: Recipes

Recipes — copy-paste ready workflows.

Other entries in this section