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 & InitPython
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.
- This section has 6 entries; this is one of them.
- See the full section index: Recipes
Other entries in this section
- Throttling: why time.sleep(0.2) appears everywhereCorelDRAW is a single-threaded STA server. Python issues commands far
- Batch undo groupWrap big jobs in BeginCommandGroup / EndCommandGroup and one Ctrl+Z in
- Verify the font before converting to curvesConverting to curves is irreversible, so the order is fixed: set the f
- Process in index-range batchesWith a lot of JSON records, run start/end slices and print "total / pa
- Skip missing data instead of raisingif not img_find_in: skip_cnt += 1; continue — a missing image gets cou