import pythoncom, win32com.client
Three steps to get running: 1. Run pip install pywin32 from the command line. Once is enough. 2. Create a .py file, paste the whole block below into it and run it. I
Signature
Notes
1. Run
pip install pywin32 from the command line. Once is enough.2. Create a .py file, paste the whole block below into it and run it. If you see "Connected to CorelDRAW", it worked.
3. From then on, paste any example's code under
if __name__ == "__main__": and run.Variables used throughout the examples:
app = the CorelDRAW application · doc = the active document ·
page = the active page · layer = the active layer ·
shape = some shape (grab the selected one with app.ActiveSelectionRange(1))Python example (runnable)
pywin32. The example assumes app / doc / page / layer are already connected.
See Connection & Init# ============================================================
# CorelDRAW Python boilerplate
# Usage: copy the whole block into cdr_base.py, or paste it at the top of your script.
# Every sample in this reference assumes app / doc / page / layer already exist.
# Requirement: pip install pywin32
# ============================================================
import time
import pythoncom
import win32com.client
# ---------- 1. Connect to CorelDRAW ----------
VER = 21 # 21=2019 22=2020 23=2021 24=2022/2023 25=2024
pythoncom.CoInitialize() # start COM for this thread; must come first
app = win32com.client.Dispatch(f"CorelDRAW.Application.{VER}")
app.Visible = True # show the UI so you can watch what happens
# ---------- 2. Get the document ----------
try:
doc = app.ActiveDocument # the document currently open
except Exception:
doc = None
if doc is None:
doc = app.CreateDocument() # no document open, create one
# ---------- 3. Get the page and layer ----------
page = doc.ActivePage # page : active page
layer = page.ActiveLayer # layer : active layer of that page (everything is drawn here)
# ---------- 4. Unit conversion (document unit here = inch) ----------
def mm(v):
"""Millimetres to document units. mm(210) gives the value for 210mm"""
return v / 25.4
# ---------- 5. Small helpers ----------
def new_page(index):
"""Ensure page index exists and return it (1-based)"""
while doc.Pages.Count < index:
doc.AddPages(1)
return doc.Pages.Item(index)
def pick():
"""First shape in the current selection"""
return app.ActiveSelectionRange(1)
def set_font(shape, font_name, size_pt=None, fallback="Source Han Sans Bold", tries=3):
"""
Set the font on a text shape and read it back to verify (a wrong name fails silently)
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 use 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
if __name__ == "__main__":
print("Connected to CorelDRAW", app.Version)
print("Active document: ", doc.FileName or "unsaved")
print("Page size: ", page.SizeWidth, "x", page.SizeHeight)
What each module is for
Beginners often assume these are two names for the same thing. The split is clear:
pythoncom— the low-level COM binding. Thread initialisation (CoInitialize), the exception type (pythoncom.com_error), HRESULT constants, ROT access (GetActiveObject), and everything at theIUnknownlevel. The class names inside your tracebacks usually come from here.win32com.client— the high-level wrapper.Dispatch,gencache, event binding, constant generation. Almost every entry point you call day to day lives here.
So you catch pythoncom.com_error, and you create objects with
win32com.client.Dispatch. Both imports are required; one alone gets you nowhere.
Three import failures and what they mean
1. ModuleNotFoundError: No module named 'pythoncom'
pywin32 is not installed in the interpreter you are running. Multiple Python
installations (system + conda + several venvs) are the usual cause: installed in A, run from B. Confirm
first:
python -c "import sys; print(sys.executable)"
python -m pip show pywin32
If those two paths do not belong to the same environment, that is your problem. Install with
python -m pip install pywin32 — always python -m pip, never bare
pip.
2. ImportError: DLL load failed while importing pythoncom
It is installed but the DLL cannot be located. Common causes: pywin32 build mismatched with the Python
major version, conda and pip overwriting each other, or leftovers from an upgrade. Try the bundled
repair script first, from an elevated prompt:
python Scripts\pywin32_postinstall.py -install
If that does not do it, remove it completely —
python -m pip uninstall pywin32, delete leftover win32*,
pythoncom*.dll, and pywintypes*.dll from site-packages, then
install again.
3. import win32com works but win32com.client raises
AttributeError
Check the current directory for a file named win32com.py or a folder named
win32com. Python imports the local module first and your own file is masquerading as the
package. That is import shadowing, unrelated to pywin32. Rename the file.
The import style to use
# preferred: explicit, readable
import pythoncom
import win32com.client
from win32com.client import gencache # only when you need the type library
# avoid: dumps Dispatch, constants and friends into the global namespace
# from win32com.client import *
Why not the star import: win32com.client exposes generic names like
Dispatch, constants, and gencache. After a star import, a function
of yours with the same name is silently replaced, and the resulting behaviour takes a long time to
explain.
Check the environment once before you start
Every example on this site assumes three things: 64-bit Windows, 64-bit Python, pywin32 installed. Get one wrong and the errors point somewhere else entirely. Run this before the first attempt:
import struct, sys
print("Python :", sys.version.split()[0])
print("bitness :", struct.calcsize("P") * 8, "bit")
print("interp :", sys.executable)
import pythoncom, win32com
print("pythoncom:", getattr(pythoncom, "__file__", "?"))
print("win32com :", win32com.__file__)
try:
from win32com import __gen_path__
print("gen_py :", __gen_path__)
except Exception:
print("gen_py : not generated yet - created on first EnsureDispatch")
The bitness line must say 64 bit. If it says 32 bit, stop there — every
Dispatch call will return Class not registered
(0x80040154) and no amount of code editing changes that.
Does import order matter
Essentially no. pythoncom and win32com.client can be imported in either
order; pywin32 sorts out its own dependencies. The one thing to avoid is
creating COM objects at import time. Module-level
app = win32com.client.Dispatch(...) makes importing the module a side-effecting operation:
a unit test that merely imports it starts a CorelDRAW process, which is miserable to trace. Put the
connection in a function and call it when needed.
About this section: Getting Started
Getting Started — the bootstrap template every example depends on.
- This section has 1 entries; this is one of them.
- See the full section index: Getting Started