or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

advanced.mdcore.mdindex.mdshapes.mdtext.mdutilities.md

utilities.mddocs/

0

# Utilities

1

2

Helper functions, unit handling, color utilities, and extension modules for specialized functionality and enhanced productivity.

3

4

## Capabilities

5

6

### Color Utilities

7

8

Functions for creating and managing color values in SVG-compatible formats.

9

10

```python { .api }

11

def rgb(r=0, g=0, b=0, mode='RGB'):

12

"""

13

Convert RGB values to SVG color string

14

15

Args:

16

r: Red component (0-255 for RGB mode, 0-100 for % mode) (default: 0)

17

g: Green component (0-255 for RGB mode, 0-100 for % mode) (default: 0)

18

b: Blue component (0-255 for RGB mode, 0-100 for % mode) (default: 0)

19

mode: Color mode 'RGB' or '%' (default: 'RGB')

20

21

Returns:

22

str: RGB color string in format 'rgb(r, g, b)' or 'rgb(r%, g%, b%)'

23

"""

24

```

25

26

**Usage Examples:**

27

28

```python

29

import svgwrite

30

31

dwg = svgwrite.Drawing('colors.svg', size=('300px', '200px'))

32

33

# RGB colors with integer values (0-255)

34

red = svgwrite.rgb(255, 0, 0) # 'rgb(255, 0, 0)'

35

green = svgwrite.rgb(0, 255, 0) # 'rgb(0, 255, 0)'

36

blue = svgwrite.rgb(0, 0, 255) # 'rgb(0, 0, 255)'

37

purple = svgwrite.rgb(128, 0, 128) # 'rgb(128, 0, 128)'

38

39

# RGB colors with percentage values

40

light_red = svgwrite.rgb(100, 50, 50, '%') # 'rgb(100%, 50%, 50%)'

41

light_green = svgwrite.rgb(50, 100, 50, '%') # 'rgb(50%, 100%, 50%)'

42

43

# Use colors in shapes

44

dwg.add(dwg.rect((20, 20), (50, 40), fill=red))

45

dwg.add(dwg.rect((80, 20), (50, 40), fill=green))

46

dwg.add(dwg.rect((140, 20), (50, 40), fill=blue))

47

dwg.add(dwg.circle((50, 120), 25, fill=purple))

48

dwg.add(dwg.circle((150, 120), 25, fill=light_red))

49

50

# Dynamic color generation

51

for i in range(5):

52

intensity = i * 50

53

color = svgwrite.rgb(intensity, 0, 255 - intensity)

54

dwg.add(dwg.rect((20 + i*40, 80), (30, 30), fill=color))

55

```

56

57

### Unit System

58

59

Comprehensive unit handling system for precise dimensional control in SVG graphics.

60

61

```python { .api }

62

class Unit:

63

"""

64

Unit class for adding measurement units to numeric values

65

"""

66

def __init__(unit='cm'):

67

"""

68

Create unit instance

69

70

Args:

71

unit: Unit string (cm, mm, px, em, etc.) (default: 'cm')

72

"""

73

74

def __rmul__(other):

75

"""

76

Add unit string to numeric value (e.g., 5*cm => '5cm')

77

78

Args:

79

other: Numeric value to apply unit to

80

81

Returns:

82

str: Value with unit suffix

83

"""

84

85

def __call__(*args):

86

"""

87

Add unit strings to multiple arguments

88

89

Args:

90

*args: List of numeric values

91

92

Returns:

93

str: Comma-separated values with units (e.g., cm(1,2,3) => '1cm,2cm,3cm')

94

"""

95

96

# Predefined unit instances

97

cm = Unit('cm') # Centimeters

98

mm = Unit('mm') # Millimeters

99

px = Unit('px') # Pixels

100

em = Unit('em') # Relative to font size

101

ex = Unit('ex') # Relative to x-height

102

inch = Unit('in') # Inches

103

pc = Unit('pc') # Picas

104

pt = Unit('pt') # Points

105

percent = Unit('%') # Percentage

106

deg = Unit('deg') # Degrees

107

grad = Unit('grad') # Gradians

108

rad = Unit('rad') # Radians

109

Hz = Unit('Hz') # Hertz

110

kHz = Unit('kHz') # Kilohertz

111

```

112

113

**Usage Examples:**

114

115

```python

116

import svgwrite

117

118

dwg = svgwrite.Drawing('units.svg', size=(500, 400))

119

120

# Using predefined units with multiplication

121

rect1 = dwg.rect(insert=(1*svgwrite.cm, 1*svgwrite.cm),

122

size=(3*svgwrite.cm, 2*svgwrite.cm),

123

fill='lightblue')

124

dwg.add(rect1)

125

126

# Using unit call syntax for coordinate lists

127

line = dwg.line(start=svgwrite.mm(10, 10),

128

end=svgwrite.mm(50, 30),

129

stroke='red', stroke_width=2*svgwrite.px)

130

dwg.add(line)

131

132

# Mixed units in single element

133

circle = dwg.circle(center=(2*svgwrite.inch, 3*svgwrite.cm),

134

r=15*svgwrite.mm,

135

fill='green')

136

dwg.add(circle)

137

138

# Font-relative units for text

139

text = dwg.text('Relative Size', insert=(50*svgwrite.px, 100*svgwrite.px),

140

font_size=2*svgwrite.em,

141

dx=svgwrite.ex(0, 1, 2, 3)) # Multiple relative offsets

142

dwg.add(text)

143

144

# Percentage units for responsive layouts

145

responsive_rect = dwg.rect(insert=(10*svgwrite.percent, 20*svgwrite.percent),

146

size=(80*svgwrite.percent, 30*svgwrite.percent),

147

fill='orange', fill_opacity=0.7)

148

dwg.add(responsive_rect)

149

150

# Angular units for rotations

151

rotated_rect = dwg.rect(insert=(200*svgwrite.px, 150*svgwrite.px),

152

size=(60*svgwrite.px, 40*svgwrite.px),

153

fill='purple',

154

transform=f'rotate({45*svgwrite.deg} 230 170)')

155

dwg.add(rotated_rect)

156

157

# Custom unit instances

158

custom_unit = svgwrite.Unit('vw') # Viewport width

159

viewport_rect = dwg.rect(insert=(5*custom_unit, 5*custom_unit),

160

size=(20*custom_unit, 15*custom_unit),

161

fill='navy', fill_opacity=0.5)

162

dwg.add(viewport_rect)

163

```

164

165

### Container Utilities

166

167

Additional container elements for advanced document organization.

168

169

```python { .api }

170

def g(**extra):

171

"""

172

Create group container for organizing related elements

173

174

Args:

175

**extra: SVG attributes (id, class, transform, etc.)

176

177

Returns:

178

Group: Group element with Transform and Presentation mixins

179

"""

180

181

def defs(**extra):

182

"""

183

Create definitions container for reusable elements

184

185

Args:

186

**extra: SVG attributes

187

188

Returns:

189

Defs: Definitions element inheriting from Group

190

"""

191

192

def use(href, insert=None, size=None, **extra):

193

"""

194

Create element reference to instantiate defined elements

195

196

Args:

197

href: Reference to element with ID (element or ID string)

198

insert: Insertion point as (x, y) tuple (default: None)

199

size: Override size as (width, height) tuple (default: None)

200

**extra: Additional SVG attributes

201

202

Returns:

203

Use: Use element with Transform, XLink, and Presentation mixins

204

"""

205

206

def symbol(**extra):

207

"""

208

Create symbol definition for reusable graphics

209

210

Args:

211

**extra: SVG attributes (viewBox, preserveAspectRatio, etc.)

212

213

Returns:

214

Symbol: Symbol element with ViewBox and Presentation mixins

215

"""

216

217

def marker(insert=None, size=None, orient=None, **extra):

218

"""

219

Create marker definition for line endings and decorations

220

221

Args:

222

insert: Reference point as (x, y) tuple (default: None)

223

size: Marker size as (width, height) tuple (default: None)

224

orient: Orientation 'auto', 'auto-start-reverse', or angle (default: None)

225

**extra: Additional marker attributes

226

227

Returns:

228

Marker: Marker element with ViewBox and Presentation mixins

229

"""

230

231

def a(href, **extra):

232

"""

233

Create hyperlink container for interactive elements

234

235

Args:

236

href: Target URL or URI for the hyperlink

237

**extra: SVG attributes (target, title, etc.)

238

239

Returns:

240

Hyperlink: Hyperlink element with Transform and Presentation mixins

241

"""

242

243

def script(href=None, content="", **extra):

244

"""

245

Create script element for client-side scripting

246

247

Args:

248

href: External script file URL (default: None)

249

content: Inline script content (default: "")

250

**extra: Additional script attributes

251

252

Returns:

253

Script: Script element for JavaScript or other client-side languages

254

"""

255

256

def style(content="", **extra):

257

"""

258

Create style element for embedded CSS

259

260

Args:

261

content: CSS stylesheet content (default: "")

262

**extra: Additional style attributes (media, type, etc.)

263

264

Returns:

265

Style: Style element for CSS stylesheets

266

"""

267

```

268

269

**Usage Examples:**

270

271

```python

272

import svgwrite

273

274

dwg = svgwrite.Drawing('containers.svg', size=('400px', '300px'))

275

276

# Create definitions

277

defs = dwg.defs()

278

279

# Define reusable symbol

280

star_symbol = dwg.symbol(id='star', viewBox='0 0 20 20')

281

star_points = [(10, 0), (12, 7), (20, 7), (14, 12), (16, 20),

282

(10, 15), (4, 20), (6, 12), (0, 7), (8, 7)]

283

star_shape = dwg.polygon(points=star_points, fill='gold', stroke='orange')

284

star_symbol.add(star_shape)

285

defs.add(star_symbol)

286

287

# Define arrow marker

288

arrow_marker = dwg.marker(insert=(0, 3), size=(10, 6), orient='auto', id='arrow')

289

arrow_path = dwg.path(d='M 0,0 L 0,6 L 9,3 z', fill='red')

290

arrow_marker.add(arrow_path)

291

defs.add(arrow_marker)

292

293

dwg.add(defs)

294

295

# Use symbols multiple times

296

star1 = dwg.use(star_symbol, insert=(50, 50), size=(40, 40))

297

dwg.add(star1)

298

299

star2 = dwg.use(star_symbol, insert=(150, 50), size=(30, 30))

300

star2.rotate(45, center=(165, 65))

301

dwg.add(star2)

302

303

star3 = dwg.use(star_symbol, insert=(250, 50), size=(50, 50))

304

star3.scale(1, 0.5) # Squashed star

305

dwg.add(star3)

306

307

# Group with transformations

308

group = dwg.g(transform='translate(100, 150) rotate(30)')

309

group.add(dwg.rect((0, 0), (60, 40), fill='lightblue'))

310

group.add(dwg.text('Grouped', insert=(10, 25), font_size='12px'))

311

dwg.add(group)

312

313

# Interactive hyperlink container

314

link_group = dwg.a(href='https://example.com', target='_blank')

315

link_group.add(dwg.rect((50, 120), (100, 30), fill='lightgreen', stroke='green'))

316

link_group.add(dwg.text('Click Me', insert=(60, 140), font_size='14px'))

317

dwg.add(link_group)

318

319

# Embedded CSS styles

320

css_styles = """

321

.glow { filter: drop-shadow(0 0 5px #00ff00); }

322

.pulse { animation: pulse 2s infinite; }

323

"""

324

style_elem = dwg.style(content=css_styles)

325

dwg.add(style_elem)

326

327

# Client-side scripting

328

js_code = """

329

function handleClick(evt) {

330

evt.target.style.fill = 'red';

331

}

332

"""

333

script_elem = dwg.script(content=js_code)

334

dwg.add(script_elem)

335

336

# Line with marker

337

arrow_line = dwg.line((50, 200), (200, 250), stroke='black', stroke_width=2,

338

marker_end='url(#arrow)')

339

dwg.add(arrow_line)

340

```

341

342

### Shape Extensions

343

344

Specialized utility functions for creating complex geometric shapes.

345

346

```python { .api }

347

# Shape generation utilities (svgwrite.extensions.shapes)

348

def ngon(num_corners, edge_length=None, radius=None, rotation=0.):

349

"""

350

Generate regular polygon vertices

351

352

Args:

353

num_corners: Number of polygon corners/sides

354

edge_length: Length of each edge (default: None)

355

radius: Radius from center to vertex (default: None)

356

rotation: Rotation angle in radians (default: 0.)

357

358

Returns:

359

list: List of (x, y) coordinate tuples for polygon vertices

360

"""

361

362

def star(spikes, r1, r2, rotation=0.):

363

"""

364

Generate star shape vertices

365

366

Args:

367

spikes: Number of star points/spikes

368

r1: Outer radius (to spike tips)

369

r2: Inner radius (to valley points)

370

rotation: Rotation angle in radians (default: 0.)

371

372

Returns:

373

list: List of (x, y) coordinate tuples for star vertices

374

"""

375

376

# Vertex transformation utilities

377

def translate(vertices, delta_x, delta_y):

378

"""

379

Translate vertex coordinates

380

381

Args:

382

vertices: List of (x, y) coordinate tuples

383

delta_x: Translation in X direction

384

delta_y: Translation in Y direction

385

386

Returns:

387

list: Translated vertex coordinates

388

"""

389

390

def scale(vertices, scale_x, scale_y):

391

"""

392

Scale vertex coordinates

393

394

Args:

395

vertices: List of (x, y) coordinate tuples

396

scale_x: Scale factor for X coordinates

397

scale_y: Scale factor for Y coordinates

398

399

Returns:

400

list: Scaled vertex coordinates

401

"""

402

403

def rotate(vertices, delta):

404

"""

405

Rotate vertices around origin

406

407

Args:

408

vertices: List of (x, y) coordinate tuples

409

delta: Rotation angle in degrees

410

411

Returns:

412

list: Rotated vertex coordinates

413

"""

414

415

def centroid(vertices):

416

"""

417

Calculate centroid (center point) of vertices

418

419

Args:

420

vertices: List of (x, y) coordinate tuples

421

422

Returns:

423

tuple: Centroid coordinates as (x, y)

424

"""

425

```

426

427

**Usage Examples:**

428

429

```python

430

import svgwrite

431

from svgwrite.extensions.shapes import ngon, star, translate, scale, rotate, centroid

432

433

dwg = svgwrite.Drawing('shapes-ext.svg', size=('500px', '400px'))

434

435

# Regular polygons

436

triangle = ngon(3, radius=30)

437

pentagon = ngon(5, edge_length=40)

438

octagon = ngon(8, radius=25, rotation=0.3927) # Rotated flat side up (22.5°)

439

440

# Position and add polygons

441

triangle_pos = translate(triangle, 80, 80)

442

pentagon_pos = translate(pentagon, 200, 80)

443

octagon_pos = translate(octagon, 350, 80)

444

445

dwg.add(dwg.polygon(triangle_pos, fill='red', stroke='darkred'))

446

dwg.add(dwg.polygon(pentagon_pos, fill='blue', stroke='darkblue'))

447

dwg.add(dwg.polygon(octagon_pos, fill='green', stroke='darkgreen'))

448

449

# Star shapes

450

star4 = star(4, r1=40, r2=20) # 4-pointed star

451

star6 = star(6, r1=35, r2=15) # 6-pointed star

452

star8 = star(8, r1=30, r2=12, rotation=0.3927) # 8-pointed star, rotated (22.5°)

453

454

# Position stars

455

star4_pos = translate(star4, 80, 200)

456

star6_pos = translate(star6, 200, 200)

457

star8_pos = translate(star8, 350, 200)

458

459

dwg.add(dwg.polygon(star4_pos, fill='orange', stroke='darkorange'))

460

dwg.add(dwg.polygon(star6_pos, fill='purple', stroke='indigo'))

461

dwg.add(dwg.polygon(star8_pos, fill='gold', stroke='goldenrod'))

462

463

# Complex transformations

464

base_shape = ngon(6, radius=25)

465

466

# Scale and position variations

467

scaled_shape = scale(base_shape, 1.5, 0.8) # Stretch horizontally

468

scaled_pos = translate(scaled_shape, 80, 320)

469

470

rotated_shape = rotate(base_shape, 30) # Rotate 30 degrees

471

rotated_pos = translate(rotated_shape, 200, 320)

472

473

# Combined transformations

474

complex_shape = rotate(scale(base_shape, 1.2, 1.8), 45)

475

complex_pos = translate(complex_shape, 350, 320)

476

477

dwg.add(dwg.polygon(scaled_pos, fill='lightblue', stroke='navy'))

478

dwg.add(dwg.polygon(rotated_pos, fill='lightgreen', stroke='forestgreen'))

479

dwg.add(dwg.polygon(complex_pos, fill='lightyellow', stroke='olive'))

480

481

# Mark centroids

482

for shape_vertices, color in [

483

(triangle_pos, 'darkred'),

484

(pentagon_pos, 'darkblue'),

485

(octagon_pos, 'darkgreen'),

486

(star4_pos, 'darkorange'),

487

(star6_pos, 'indigo'),

488

(star8_pos, 'goldenrod')

489

]:

490

center = centroid(shape_vertices)

491

dwg.add(dwg.circle(center, 2, fill=color))

492

```

493

494

### Inkscape Extensions

495

496

Specialized functionality for enhanced compatibility with Inkscape SVG editor.

497

498

```python { .api }

499

# Inkscape extension (svgwrite.extensions.inkscape)

500

class Inkscape:

501

"""

502

Support for Inkscape-specific features and extensions

503

"""

504

def __init__(drawing):

505

"""

506

Initialize Inkscape extension for a drawing

507

508

Args:

509

drawing: SVGWrite Drawing instance

510

"""

511

512

def layer(label=None, locked=False, **kwargs):

513

"""

514

Create Inkscape layer (special group with layer attributes)

515

516

Args:

517

label: Layer name for Inkscape layer panel (default: None)

518

locked: Lock layer to prevent editing (default: False)

519

**kwargs: Additional group attributes

520

521

Returns:

522

Group: Group element with Inkscape layer attributes

523

"""

524

```

525

526

**Usage Examples:**

527

528

```python

529

import svgwrite

530

from svgwrite.extensions.inkscape import Inkscape

531

532

dwg = svgwrite.Drawing('inkscape.svg', size=('400px', '300px'))

533

534

# Initialize Inkscape extension

535

inkscape = Inkscape(dwg)

536

537

# Create layers for organized editing in Inkscape

538

background_layer = inkscape.layer(label='Background', locked=False)

539

background_layer.add(dwg.rect((0, 0), ('100%', '100%'), fill='lightgray'))

540

dwg.add(background_layer)

541

542

shapes_layer = inkscape.layer(label='Shapes', locked=False)

543

shapes_layer.add(dwg.circle((100, 100), 40, fill='red'))

544

shapes_layer.add(dwg.rect((200, 60), (80, 80), fill='blue'))

545

dwg.add(shapes_layer)

546

547

text_layer = inkscape.layer(label='Text', locked=True) # Locked layer

548

text_layer.add(dwg.text('Layer Text', insert=(50, 200), font_size='18px'))

549

dwg.add(text_layer)

550

551

effects_layer = inkscape.layer(label='Effects')

552

# Add elements with filters or other effects

553

gradient = dwg.linearGradient((0, 0), (100, 0), id='grad')

554

gradient.add_stop_color(0, 'yellow')

555

gradient.add_stop_color(1, 'orange')

556

dwg.defs.add(gradient)

557

558

effects_layer.add(dwg.ellipse((300, 150), (60, 30),

559

fill=gradient.get_paint_server()))

560

dwg.add(effects_layer)

561

```

562

563

### Version Information

564

565

Access to library version details and compatibility information.

566

567

```python { .api }

568

# Version constants

569

VERSION = "1.4.3" # String version number

570

__version__ = "1.4.3" # Standard Python version attribute

571

version = (1, 4, 3, 'release') # Tuple version information

572

```

573

574

**Usage Examples:**

575

576

```python

577

import svgwrite

578

579

# Check library version

580

print(f"SVGWrite version: {svgwrite.VERSION}")

581

print(f"Version tuple: {svgwrite.version}")

582

583

# Version-dependent feature usage

584

if svgwrite.version >= (1, 4, 0):

585

# Use features available in 1.4.0+

586

dwg = svgwrite.Drawing('modern.svg', profile='full')

587

# Add advanced features...

588

else:

589

# Fallback for older versions

590

dwg = svgwrite.Drawing('basic.svg', profile='tiny')

591

# Use basic features only...

592

593

# Include version in SVG metadata

594

dwg = svgwrite.Drawing('versioned.svg')

595

dwg.add(dwg.desc(f'Created with SVGWrite {svgwrite.VERSION}'))

596

```