or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

tessl/pypi-cairosvg

A Simple SVG Converter based on Cairo that converts SVG files to PDF, EPS, PostScript, and PNG formats

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
pypipkg:pypi/cairosvg@2.8.x

To install, run

npx @tessl/cli install tessl/pypi-cairosvg@2.8.0

0

# CairoSVG

1

2

A Simple SVG Converter based on Cairo that converts SVG files to PDF, EPS, PostScript (PS), and PNG formats. CairoSVG provides both a Python API and command-line interface for programmatic and terminal usage, supporting SVG 1.1 specification with comprehensive CSS styling, gradient fills, patterns, and text rendering capabilities.

3

4

## Package Information

5

6

- **Package Name**: CairoSVG

7

- **Language**: Python

8

- **Installation**: `pip install CairoSVG`

9

- **Python Requirements**: Python 3.9+

10

- **Dependencies**: cairocffi, cssselect2, defusedxml, pillow, tinycss2

11

12

## Core Imports

13

14

```python

15

import cairosvg

16

```

17

18

For direct access to conversion functions:

19

20

```python

21

from cairosvg import svg2pdf, svg2png, svg2ps, svg2eps, svg2svg

22

```

23

24

For access to Surface classes:

25

26

```python

27

from cairosvg import SURFACES

28

from cairosvg.surface import Surface, PDFSurface, PNGSurface, PSSurface, EPSSurface, SVGSurface

29

```

30

31

## Basic Usage

32

33

```python

34

import cairosvg

35

36

# Convert SVG file to PDF

37

cairosvg.svg2pdf(url='image.svg', write_to='output.pdf')

38

39

# Convert SVG file to PNG with custom DPI

40

cairosvg.svg2png(url='image.svg', write_to='output.png', dpi=150)

41

42

# Convert SVG string to PDF bytes

43

svg_string = '''<svg width="100" height="100" xmlns="http://www.w3.org/2000/svg">

44

<circle cx="50" cy="50" r="40" fill="red"/>

45

</svg>'''

46

pdf_bytes = cairosvg.svg2pdf(bytestring=svg_string.encode('utf-8'))

47

48

# Convert with file objects

49

with open('input.svg', 'rb') as svg_file:

50

with open('output.png', 'wb') as png_file:

51

cairosvg.svg2png(file_obj=svg_file, write_to=png_file, dpi=300)

52

```

53

54

## Capabilities

55

56

### SVG to PDF Conversion

57

58

Converts SVG files to PDF format with vector graphics preservation.

59

60

```python { .api }

61

def svg2pdf(bytestring=None, *, file_obj=None, url=None, dpi=96,

62

parent_width=None, parent_height=None, scale=1, unsafe=False,

63

background_color=None, negate_colors=False, invert_images=False,

64

write_to=None, output_width=None, output_height=None):

65

"""

66

Convert an SVG document to PDF format.

67

68

Parameters:

69

- bytestring (bytes, optional): The SVG source as a byte-string

70

- file_obj (file-like, optional): A file-like object containing SVG data

71

- url (str, optional): A filename or URL to an SVG file

72

- dpi (float): The ratio between 1 inch and 1 pixel (default: 96)

73

- parent_width (float, optional): The width of the parent container in pixels

74

- parent_height (float, optional): The height of the parent container in pixels

75

- scale (float): The output scaling factor (default: 1)

76

- unsafe (bool): Allow external file access, XML entities and very large files (default: False)

77

- background_color (str, optional): Background color for the output

78

- negate_colors (bool): Replace every vector color with its complement (default: False)

79

- invert_images (bool): Replace every raster pixel with its complementary color (default: False)

80

- write_to (str or file-like, optional): Output filename or file-like object

81

- output_width (float, optional): Desired output width in pixels

82

- output_height (float, optional): Desired output height in pixels

83

84

Returns:

85

bytes: PDF data if write_to is None, otherwise None

86

"""

87

```

88

89

### SVG to PNG Conversion

90

91

Converts SVG files to PNG raster format with customizable resolution.

92

93

```python { .api }

94

def svg2png(bytestring=None, *, file_obj=None, url=None, dpi=96,

95

parent_width=None, parent_height=None, scale=1, unsafe=False,

96

background_color=None, negate_colors=False, invert_images=False,

97

write_to=None, output_width=None, output_height=None):

98

"""

99

Convert an SVG document to PNG format.

100

101

Parameters:

102

- bytestring (bytes, optional): The SVG source as a byte-string

103

- file_obj (file-like, optional): A file-like object containing SVG data

104

- url (str, optional): A filename or URL to an SVG file

105

- dpi (float): The ratio between 1 inch and 1 pixel (default: 96)

106

- parent_width (float, optional): The width of the parent container in pixels

107

- parent_height (float, optional): The height of the parent container in pixels

108

- scale (float): The output scaling factor (default: 1)

109

- unsafe (bool): Allow external file access, XML entities and very large files (default: False)

110

- background_color (str, optional): Background color for the output

111

- negate_colors (bool): Replace every vector color with its complement (default: False)

112

- invert_images (bool): Replace every raster pixel with its complementary color (default: False)

113

- write_to (str or file-like, optional): Output filename or file-like object

114

- output_width (float, optional): Desired output width in pixels

115

- output_height (float, optional): Desired output height in pixels

116

117

Returns:

118

bytes: PNG data if write_to is None, otherwise None

119

"""

120

```

121

122

### SVG to PostScript Conversion

123

124

Converts SVG files to PostScript format for printing and publishing.

125

126

```python { .api }

127

def svg2ps(bytestring=None, *, file_obj=None, url=None, dpi=96,

128

parent_width=None, parent_height=None, scale=1, unsafe=False,

129

background_color=None, negate_colors=False, invert_images=False,

130

write_to=None, output_width=None, output_height=None):

131

"""

132

Convert an SVG document to PostScript format.

133

134

Parameters:

135

- bytestring (bytes, optional): The SVG source as a byte-string

136

- file_obj (file-like, optional): A file-like object containing SVG data

137

- url (str, optional): A filename or URL to an SVG file

138

- dpi (float): The ratio between 1 inch and 1 pixel (default: 96)

139

- parent_width (float, optional): The width of the parent container in pixels

140

- parent_height (float, optional): The height of the parent container in pixels

141

- scale (float): The output scaling factor (default: 1)

142

- unsafe (bool): Allow external file access, XML entities and very large files (default: False)

143

- background_color (str, optional): Background color for the output

144

- negate_colors (bool): Replace every vector color with its complement (default: False)

145

- invert_images (bool): Replace every raster pixel with its complementary color (default: False)

146

- write_to (str or file-like, optional): Output filename or file-like object

147

- output_width (float, optional): Desired output width in pixels

148

- output_height (float, optional): Desired output height in pixels

149

150

Returns:

151

bytes: PostScript data if write_to is None, otherwise None

152

"""

153

```

154

155

### SVG to EPS Conversion

156

157

Converts SVG files to Encapsulated PostScript format for document embedding.

158

159

```python { .api }

160

def svg2eps(bytestring=None, *, file_obj=None, url=None, dpi=96,

161

parent_width=None, parent_height=None, scale=1, unsafe=False,

162

background_color=None, negate_colors=False, invert_images=False,

163

write_to=None, output_width=None, output_height=None):

164

"""

165

Convert an SVG document to Encapsulated PostScript format.

166

167

Parameters:

168

- bytestring (bytes, optional): The SVG source as a byte-string

169

- file_obj (file-like, optional): A file-like object containing SVG data

170

- url (str, optional): A filename or URL to an SVG file

171

- dpi (float): The ratio between 1 inch and 1 pixel (default: 96)

172

- parent_width (float, optional): The width of the parent container in pixels

173

- parent_height (float, optional): The height of the parent container in pixels

174

- scale (float): The output scaling factor (default: 1)

175

- unsafe (bool): Allow external file access, XML entities and very large files (default: False)

176

- background_color (str, optional): Background color for the output

177

- negate_colors (bool): Replace every vector color with its complement (default: False)

178

- invert_images (bool): Replace every raster pixel with its complementary color (default: False)

179

- write_to (str or file-like, optional): Output filename or file-like object

180

- output_width (float, optional): Desired output width in pixels

181

- output_height (float, optional): Desired output height in pixels

182

183

Returns:

184

bytes: EPS data if write_to is None, otherwise None

185

"""

186

```

187

188

### SVG to SVG Conversion

189

190

Converts and processes SVG files to normalized SVG format.

191

192

```python { .api }

193

def svg2svg(bytestring=None, *, file_obj=None, url=None, dpi=96,

194

parent_width=None, parent_height=None, scale=1, unsafe=False,

195

background_color=None, negate_colors=False, invert_images=False,

196

write_to=None, output_width=None, output_height=None):

197

"""

198

Convert an SVG document to SVG format (normalization/processing).

199

200

Parameters:

201

- bytestring (bytes, optional): The SVG source as a byte-string

202

- file_obj (file-like, optional): A file-like object containing SVG data

203

- url (str, optional): A filename or URL to an SVG file

204

- dpi (float): The ratio between 1 inch and 1 pixel (default: 96)

205

- parent_width (float, optional): The width of the parent container in pixels

206

- parent_height (float, optional): The height of the parent container in pixels

207

- scale (float): The output scaling factor (default: 1)

208

- unsafe (bool): Allow external file access, XML entities and very large files (default: False)

209

- background_color (str, optional): Background color for the output

210

- negate_colors (bool): Replace every vector color with its complement (default: False)

211

- invert_images (bool): Replace every raster pixel with its complementary color (default: False)

212

- write_to (str or file-like, optional): Output filename or file-like object

213

- output_width (float, optional): Desired output width in pixels

214

- output_height (float, optional): Desired output height in pixels

215

216

Returns:

217

bytes: SVG data if write_to is None, otherwise None

218

"""

219

```

220

221

## Advanced Usage - Surface Classes

222

223

For advanced usage and fine-grained control over the conversion process, you can use Surface classes directly.

224

225

### Surface Base Class

226

227

```python { .api }

228

class Surface:

229

"""

230

Abstract base class for CairoSVG surfaces.

231

232

The width and height attributes are in device units (pixels for PNG, else points).

233

The context_width and context_height attributes are in user units (i.e. in pixels).

234

"""

235

236

@classmethod

237

def convert(cls, bytestring=None, *, file_obj=None, url=None, dpi=96,

238

parent_width=None, parent_height=None, scale=1, unsafe=False,

239

background_color=None, negate_colors=False,

240

invert_images=False, write_to=None, output_width=None,

241

output_height=None, **kwargs):

242

"""Convert an SVG document to the format for this class."""

243

244

def __init__(self, tree, output, dpi, parent_surface=None,

245

parent_width=None, parent_height=None,

246

scale=1, output_width=None, output_height=None,

247

background_color=None, map_rgba=None, map_image=None):

248

"""Create the surface from a filename or a file-like object."""

249

250

def finish(self):

251

"""Read the surface content."""

252

253

def draw(self, node):

254

"""Draw node and its children."""

255

256

@property

257

def points_per_pixel(self):

258

"""Surface resolution."""

259

260

@property

261

def device_units_per_user_units(self):

262

"""Ratio between Cairo device units and user units."""

263

```

264

265

### Concrete Surface Classes

266

267

```python { .api }

268

class PDFSurface(Surface):

269

"""A surface that writes in PDF format."""

270

271

class PSSurface(Surface):

272

"""A surface that writes in PostScript format."""

273

274

class EPSSurface(Surface):

275

"""A surface that writes in Encapsulated PostScript format."""

276

277

class PNGSurface(Surface):

278

"""A surface that writes in PNG format."""

279

280

class SVGSurface(Surface):

281

"""A surface that writes in SVG format."""

282

```

283

284

## Parser Classes

285

286

For advanced SVG parsing and tree manipulation:

287

288

```python { .api }

289

class Tree:

290

"""SVG tree parser class."""

291

292

def __new__(cls, **kwargs):

293

"""Create a new Tree instance."""

294

295

class Node:

296

"""SVG node parser class."""

297

```

298

299

## Constants

300

301

```python { .api }

302

VERSION: str

303

__version__: str # Same as VERSION

304

SURFACES: dict # Mapping of format names to Surface classes

305

```

306

307

## Exceptions

308

309

```python { .api }

310

class PointError(Exception):

311

"""Exception raised when parsing a point fails."""

312

```

313

314

## Command Line Usage

315

316

CairoSVG can also be used from the command line:

317

318

```bash

319

# Convert SVG to PDF

320

cairosvg input.svg -o output.pdf

321

322

# Convert with specific format

323

cairosvg input.svg -f png -o output.png

324

325

# Convert with custom DPI

326

cairosvg input.svg -f png -d 300 -o output.png

327

328

# Convert with custom dimensions

329

cairosvg input.svg -f png -W 800 -H 600 -o output.png

330

331

# Convert from stdin to stdout

332

cat input.svg | cairosvg -f pdf > output.pdf

333

```

334

335

## Error Handling

336

337

```python

338

from cairosvg import svg2pdf, PointError

339

340

try:

341

svg2pdf(url='malformed.svg', write_to='output.pdf')

342

except PointError as e:

343

print(f"SVG parsing error: {e}")

344

except ValueError as e:

345

print(f"Invalid SVG dimensions: {e}")

346

except FileNotFoundError as e:

347

print(f"File not found: {e}")

348

```

349

350

## Security Considerations

351

352

- **unsafe parameter**: The `unsafe=True` parameter allows external file access, XML entities, and very large files. This can make your application vulnerable to XXE attacks and various DoS attacks. Only use when you trust the SVG source.

353

- **Resource limits**: Large SVG files or complex graphics can consume significant memory and processing time

354

- **External resources**: By default, CairoSVG blocks external resources for security