or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

font-management.mdindex.mdsvg-conversion.mdsvg-path-processing.md

svg-conversion.mddocs/

0

# SVG Conversion

1

2

Core functionality for converting SVG files and streams to ReportLab Drawing objects. This module handles SVG parsing, processing, and conversion to ReportLab's graphics format.

3

4

## Capabilities

5

6

### Main Conversion Function

7

8

Converts SVG files to ReportLab Drawing objects with support for various input formats including compressed SVG files.

9

10

```python { .api }

11

def svg2rlg(path, resolve_entities=False, **kwargs):

12

"""

13

Convert an SVG file to an RLG Drawing object.

14

15

Parameters:

16

- path: str, pathlib.Path, or file-like object - SVG file path or stream

17

- resolve_entities: bool - Enable XML entity resolution for external entities

18

- **kwargs: Additional arguments passed to SvgRenderer

19

20

Returns:

21

Drawing: ReportLab Drawing object or None if conversion fails

22

"""

23

```

24

25

**Usage Examples:**

26

27

```python

28

from svglib.svglib import svg2rlg

29

from reportlab.graphics import renderPDF

30

import io

31

32

# Convert from file path

33

drawing = svg2rlg("diagram.svg")

34

35

# Convert from pathlib.Path

36

from pathlib import Path

37

svg_path = Path("graphics/chart.svg")

38

drawing = svg2rlg(svg_path)

39

40

# Convert from compressed SVG

41

drawing = svg2rlg("compressed_graphic.svgz") # Automatically decompressed

42

43

# Convert from file-like object

44

svg_content = '<svg>...</svg>'

45

drawing = svg2rlg(io.StringIO(svg_content))

46

47

# Enable entity resolution for SVGs with external references

48

drawing = svg2rlg("complex.svg", resolve_entities=True)

49

50

# Use converted drawing

51

if drawing:

52

renderPDF.drawToFile(drawing, "output.pdf")

53

```

54

55

### File Loading

56

57

Low-level function for loading and parsing SVG files using lxml.

58

59

```python { .api }

60

def load_svg_file(path, resolve_entities=False):

61

"""

62

Load and parse an SVG file using lxml.

63

64

Parameters:

65

- path: str or file-like object - SVG file path or stream

66

- resolve_entities: bool - Enable XML entity resolution

67

68

Returns:

69

Element: Parsed SVG root element or None if parsing fails

70

"""

71

```

72

73

### Rendering Classes

74

75

#### SvgRenderer

76

77

Main renderer class that converts SVG DOM to ReportLab Drawing objects.

78

79

```python { .api }

80

class SvgRenderer:

81

"""

82

Renderer that renders an SVG file on a ReportLab Drawing instance.

83

"""

84

85

def __init__(self, path, color_converter=None, parent_svgs=None, font_map=None):

86

"""

87

Initialize SVG renderer.

88

89

Parameters:

90

- path: str - Source SVG file path

91

- color_converter: callable, optional - Custom color conversion function

92

- parent_svgs: list, optional - Parent SVG chain for circular reference detection

93

- font_map: FontMap, optional - Custom font mapping instance

94

"""

95

96

def render(self, svg_root):

97

"""

98

Render SVG root element to ReportLab Drawing.

99

100

Parameters:

101

- svg_root: Element - Parsed SVG root element

102

103

Returns:

104

Drawing: ReportLab Drawing object

105

"""

106

```

107

108

#### Svg2RlgAttributeConverter

109

110

Converts SVG attributes to ReportLab format.

111

112

```python { .api }

113

class Svg2RlgAttributeConverter:

114

"""A concrete SVG to RLG attribute converter."""

115

116

def __init__(self, color_converter=None, font_map=None):

117

"""

118

Initialize attribute converter.

119

120

Parameters:

121

- color_converter: callable, optional - Custom color conversion function

122

- font_map: FontMap, optional - Font mapping instance

123

"""

124

125

def convertLength(self, svgAttr, em_base=12, attr_name=None, default=0.0):

126

"""

127

Convert SVG length to points.

128

129

Parameters:

130

- svgAttr: str - SVG length attribute value

131

- em_base: float - Base size for 'em' units

132

- attr_name: str, optional - Attribute name for context

133

- default: float - Default value if conversion fails

134

135

Returns:

136

float: Length in points

137

"""

138

```

139

140

#### Svg2RlgShapeConverter

141

142

Converts SVG shape elements to ReportLab shapes.

143

144

```python { .api }

145

class Svg2RlgShapeConverter:

146

"""Converts SVG shape elements to ReportLab shapes."""

147

148

def __init__(self, path, attrConverter):

149

"""

150

Initialize shape converter.

151

152

Parameters:

153

- path: str - Source SVG file path

154

- attrConverter: Svg2RlgAttributeConverter - Attribute converter instance

155

"""

156

157

def get_handled_shapes(self):

158

"""

159

Get list of SVG element names this converter can handle.

160

161

Returns:

162

list: SVG element names

163

"""

164

```

165

166

### Specialized Shape Classes

167

168

#### NoStrokePath

169

170

Path object that never receives stroke width regardless of style properties.

171

172

```python { .api }

173

class NoStrokePath(Path):

174

"""

175

Path object that never gets stroke width.

176

Useful for workaround of ReportLab rendering issues.

177

"""

178

179

def __init__(self, *args, copy_from=None, **kwargs):

180

"""

181

Initialize NoStrokePath.

182

183

Parameters:

184

- *args: Path constructor arguments

185

- copy_from: Path, optional - Path to copy properties from

186

- **kwargs: Additional keyword arguments

187

"""

188

```

189

190

#### ClippingPath

191

192

Path object for SVG clipping operations.

193

194

```python { .api }

195

class ClippingPath(Path):

196

"""Path object for SVG clipping operations."""

197

198

def __init__(self, *args, **kwargs):

199

"""Initialize ClippingPath with standard Path arguments."""

200

```

201

202

### Exception Classes

203

204

#### CircularRefError

205

206

Exception raised when circular references are detected in SVG files.

207

208

```python { .api }

209

class CircularRefError(Exception):

210

"""Exception for circular reference detection in SVG processing."""

211

```

212

213

### Utility Functions

214

215

#### nudge_points

216

217

Adjusts coordinate points to work around ReportLab's handling of zero-size shapes.

218

219

```python { .api }

220

def nudge_points(points):

221

"""

222

Nudge first coordinate if all coordinate pairs are identical.

223

Works around ReportLab's decision to hide shapes of size zero.

224

225

Parameters:

226

- points: list - List of coordinate values [x1, y1, x2, y2, ...]

227

"""

228

```

229

230

#### copy_shape_properties

231

232

Copies properties from one ReportLab shape to another.

233

234

```python { .api }

235

def copy_shape_properties(source_shape, dest_shape):

236

"""

237

Copy properties from source shape to destination shape.

238

239

Parameters:

240

- source_shape: Shape - Source ReportLab shape

241

- dest_shape: Shape - Destination ReportLab shape

242

"""

243

```

244

245

#### monkeypatch_reportlab

246

247

Applies patches to ReportLab for better SVG compatibility.

248

249

```python { .api }

250

def monkeypatch_reportlab():

251

"""Apply patches to ReportLab for better SVG compatibility."""

252

```

253

254

## Types

255

256

### Box

257

258

Named tuple for bounding box representation.

259

260

```python { .api }

261

Box = namedtuple('Box', ['x', 'y', 'width', 'height'])

262

```

263

264

**Usage:**

265

```python

266

from svglib.svglib import Box

267

268

# Create bounding box

269

bbox = Box(x=10, y=20, width=100, height=50)

270

print(f"Box: {bbox.x}, {bbox.y}, {bbox.width}x{bbox.height}")

271

```