Document

The document, its shortcuts and its export entry points.

class Document(width: float | Length | None = None, height: float | Length | None = None, *, size: str | PageSize | None = None, root: Svg | None = None, theme: Theme | str | None = None, **kwargs: Any)[source]

Bases: Building, Sizing, Theming, Typography, Output, Access, InkscapeData, ElementFactory

An SVG document under construction.

Shortcut methods (doc.circle(...), doc.linear_gradient(...)) build an element, add it and return it; definitions go into <defs>. Containers returned by shortcuts nest when used with with.

Parameters:
  • width (float or Length, optional) – Canvas size; a matching viewBox is added unless one is given. Defaults to None, which sizes the canvas from the content on output.

  • height (float or Length, optional) – Canvas size; a matching viewBox is added unless one is given. Defaults to None, which sizes the canvas from the content on output.

  • size (str or PageSize, optional) – A PageSize (svg.size.a4), or a named size instead of width and height: "a4", "letter", "slide-16:9", "instagram-post", … (see size), with -landscape or -portrait appended to turn it. Paper sizes are in millimetres or inches, so the viewBox counts in those units. Defaults to None.

  • root (Svg, optional) – Use an existing root instead of creating one. Defaults to None.

  • theme (Theme or str, optional) – Styles elements marked with as_role. Defaults to None, which keeps the theme that wrote the theme sheet of an existing root, else takes Theme.current() ("light" outside a with theme: block).

  • **kwargs – Forwarded to Svg.

Raises:
  • TypeError – If size is given together with width or height.

  • ValueError – If size is not a registered name.

See also

svgwriter.model.elements.Svg

The root element wrapped by a document.

svgwriter.library.preset.size

Add a named size.

Notes

doc += element (or a list) adds at the insertion point. Elements used as references (fill=gradient, clip_path=clip) go into <defs> automatically; doc.define(x) or doc.defs += x does it explicitly.

Examples

>>> from svgwriter import Rect
>>> doc = Document(100, 100)
>>> glow = doc.radial_gradient(cx=0.5, cy=0.5, r=0.5)
>>> with doc.group(fill="red") as g:
...     _ = doc.rect(10, 10, 20, 20)
...     _ = doc.circle(50, 50, 10, fill=glow)
>>> len(g)
2
>>> doc += Rect(0, 0, 5, 5)
>>> doc.root[-1].tag
'rect'
>>> page = Document(size="a4")
>>> page.root.get("width"), page.root.get("viewBox").width
(Length(value=210.0, unit=<Unit.MM: 'mm'>), 210.0)
root
property theme: Theme

The theme that styles elements marked with as_role; assign a theme or a registered name.

Examples

>>> import svgwriter as svg
>>> doc = svg.Document(10, 10)
>>> doc.theme.name
'light'
>>> doc.theme = "dark"
>>> doc.theme.name
'dark'
What the code above draws
classmethod from_string(text: str | bytes, format: str = 'svg', *, strictness: Strictness | None = None, **options: Any) → Document[source]

Parse text in any registered format into a document: SVG by default, or Mermaid, DOT, TikZ, …

Text formats that are usually files ("mermaid", "dot", "tikz", "markdown", "txt", "eps", …) are read from the string itself, with the same importer as open().

Parameters:
  • text (str or bytes) – The source; str is encoded as UTF-8 for formats read as bytes.

  • format (str, optional) – A format name or extension (see svg.formats.readers()). Defaults to "svg".

  • strictness (Strictness, optional) – How SVG treats unknown elements and unsupported attributes. Defaults to Strictness.LENIENT. SVG only.

  • **options (Any) – Options of the importer (for example theme= for Mermaid). SVG takes only theme=, the theme to restyle the document with (by default the one that wrote it is kept).

Returns:

Document – A document wrapping the parsed root.

Raises:
  • SVGParseError – If the text is malformed or, when strict, unsupported.

  • ValueError – If the root element is not <svg>, or format is not a registered importer.

  • TypeError – If strictness is given for a format other than SVG, or SVG is given an option other than theme.

See also

open

Read a file in any registered format.

Examples

>>> doc = Document.from_string('<svg xmlns="http://www.w3.org/2000/svg"><rect width="4" height="4"/></svg>')
>>> [element.tag for element in doc]
['rect']
>>> chart = Document.from_string("flowchart LR\n  A --> B", "mermaid")
>>> len(chart.root.children) > 0
True
classmethod writing(path: AnyPath, width: float, height: float, **kwargs: Any) → Generator[Document, None, None][source]

Build a document and save it to path when the block exits.

Parameters:
  • path (str or os.PathLike) – Where to save the document.

  • width (float) – Canvas size.

  • height (float) – Canvas size.

  • **kwargs – Forwarded to the constructor; options (a SerializeOptions) is used when saving.

Yields:

Document – The document to draw into.

See also

save

Save an existing document.

Examples

>>> import tempfile, pathlib
>>> with tempfile.TemporaryDirectory() as folder:
...     path = pathlib.Path(folder) / "a.svg"
...     with Document.writing(path, 10, 10) as doc:
...         _ = doc.circle(5, 5, 2)
...     print("<circle" in path.read_text(encoding="utf-8"))
True
__getitem__(key: int | slice | str) → Element | list[Element]

doc[0] (top-level content by position), doc[1:3] or doc["logo"] (any element by id or label).

A string is looked up as an id first; when no element has that id, the element whose label (inkscape:label, the name Inkscape shows in its Objects panel) matches is returned.

Parameters:

key (int, slice or str) – A position or slice among the top-level content, or an element id or label.

Returns:

Element or list of Element – The element, or a list for a slice.

Raises:

IndexError, KeyError – When nothing is at that position or has that id or label, or when several elements share the label.

Examples

>>> from svgwriter import Document
>>> doc = Document(10, 10)
>>> _ = doc.rect(0, 0, 5, 5, id="logo")
>>> _ = doc.circle(5, 5, 2, inkscape_label="Sun")
>>> doc[0] is doc["logo"], doc["Sun"].tag
(True, 'circle')
What the code above draws
__iadd__(elements: Element | SupportsSVG | Iterable[Element]) → Self
__iter__() → Iterator[Element]

Top-level content elements (<defs>, <style>, <title>, <desc> skipped).

Use doc.root.iter() to walk the whole tree.

__len__() → int
add(element: Element | SupportsSVG) → Element

Add element at the insertion point and return it.

Objects from other libraries that implement _repr_svg_ (plots, diagrams, formulas) are parsed and added as a <g> holding their <svg>, so they can be moved and scaled like any group.

Parameters:

element (Element or SupportsSVG) – The element, or an object providing _repr_svg_.

Returns:

Element – The added element; a <g> when a foreign object was converted.

Raises:

TypeError – If a _repr_svg_ object returns no SVG.

See also

define

Add to <defs> instead.

Examples

>>> import svgwriter as svg
>>> doc = svg.Document(10, 10)
>>> rect = doc.add(svg.Rect(0, 0, 5, 5))
>>> rect.parent is doc.root
True
What the code above draws
at(seconds: float) → Document

A static copy with every SMIL animation applied at seconds (and removed).

Parameters:

seconds (float) – Seconds since the document began.

Returns:

Document – The frame at that moment; this document is unchanged.

See also

render_animation

Uses this for each frame, so SMIL plays without update.

Notes

Supports animate, set, animateColor, animateTransform and animateMotion with clock timing, repeatCount, repeatDur, fill="freeze", values/from/to/by, keyTimes, discrete mode and additive="sum". Event-based begins and spline timing are treated as their clock-based, linear equivalents.

Examples

>>> import svgwriter as svg
>>> doc = svg.Document(100, 20)
>>> ball = doc.circle(10, 10, 5)
>>> _ = ball.append(svg.Animate(attribute_name="cx", from_=10, to=90, dur=2))
>>> doc.at(1.0)[0].get("cx")
'50'
What the code above draws
property auto_size: bool

Whether the canvas is computed from the content (no width, height or viewBox set).

Examples

>>> from svgwriter import Document, Rect
>>> Document().auto_size, Document(10, 10).auto_size
(True, False)
content_bounds(padding: float = 0.0) → BBox | None

Union of the top-level content’s stroke-inclusive bounds, grown by padding.

Parameters:

padding (float, optional) – Margin added on every side. Defaults to 0.0.

Returns:

BBox or None – The bounds, or None when the content has no measurable shape.

See also

fit

Apply the bounds as the canvas size.

Examples

>>> from svgwriter import Document, Rect
>>> doc = Document()
>>> doc.content_bounds() is None
True
>>> _ = doc.rect(10, 10, 20, 20)
>>> doc.content_bounds(padding=2)
BBox(x=8.0, y=8.0, width=24.0, height=24.0)
What the code above draws
property current: Element

the innermost open container.

Examples

>>> import svgwriter as svg
>>> doc = svg.Document(10, 10)
>>> doc.current is doc.root
True
>>> with doc.group() as g:
...     print(doc.current is g)
True
What the code above draws
Type:

Where add() inserts

define(element: E) → E

Put element in <defs> (giving it an id) and return it.

Parameters:

element (Element) – The element to define; it receives an id if it has none.

Returns:

Element – The same element, now inside <defs>.

See also

add

Add at the insertion point instead.

Examples

>>> import svgwriter as svg
>>> doc = svg.Document(10, 10)
>>> cell = doc.define(svg.Rect(0, 0, 1, 1))
>>> cell.parent is doc.defs, cell.id.startswith("rect")
(True, True)
What the code above draws
property defs: Defs

The root <defs>, created on first use; doc.defs += x adds to it.

Examples

>>> import svgwriter as svg
>>> doc = svg.Document(10, 10)
>>> doc.defs += svg.Rect(0, 0, 1, 1, id="cell")
>>> doc.defs.tag, len(doc.defs)
('defs', 1)
What the code above draws
describe(text: str) → Desc

Add a <desc> at the insertion point.

Parameters:

text (str) – The description.

Returns:

Desc – The new element.

See also

title

Add a short name.

Examples

>>> import svgwriter as svg
>>> doc = svg.Document(10, 10)
>>> doc.describe("A blue square").children
['A blue square']
What the code above draws
embed_fonts(*typefaces: Typeface) → StyleElement | None

Add @font-face rules carrying the used fonts, so the SVG file shows them anywhere.

Only the faces the text actually uses are written, each once, as base64 data URIs in a <style> at the top of the document. Call it once, after the text is in place.

Parameters:

*typefaces (Typeface) – The families to embed. Defaults to every Typeface made in this session.

Returns:

StyleElement or None – The new <style>, or None when no text uses the typefaces.

See also

used_faces

The faces that would be written.

Typeface.css

The rules of one family.

Examples

>>> import svgwriter as svg
>>> sans = svg.Typeface("sans-serif")
>>> doc = svg.Document(100, 40)
>>> _ = doc.text("Hi", x=0, y=20, font=sans)
>>> "@font-face" in doc.embed_fonts(sans).css
True
What the code above draws
export(format: str, **options: Any) → bytes | str

This document in format ("png", "pdf", "tikz", … or an extension).

svg.formats.writers() lists the formats.

Parameters:
  • format (str) – Format name or extension.

  • **options – Exporter options.

Returns:

bytes or str – The encoded document; text formats return str.

See also

save

Write to a file.

Examples

>>> from svgwriter import Document, Rect
>>> Document(10, 10).export("png")[1:4]
b'PNG'
property export_hints: ExportHints

Inkscape’s export resolution, file name and document units; assign to change them.

Raster exports (doc.save("a.png")) use the stored resolution when no scale, dpi or size is given.

Examples

>>> import svgwriter as svg
>>> doc = svg.Document(10, 10)
>>> doc.export_hints = svg.inkscape.ExportHints(dpi=192)
>>> png = doc.export("png")
>>> doc.export_hints.dpi, int.from_bytes(png[16:20], "big")
(192.0, 20)
What the code above draws
fit(padding: float = 0.0) → Self

Set viewBox, width and height to the content bounds (plus padding) and return self.

Parameters:

padding (float, optional) – Margin added on every side. Defaults to 0.0.

Returns:

Document – This document, for chaining.

See also

content_bounds

The bounds that are applied.

Examples

>>> from svgwriter import Document, Rect
>>> doc = Document()
>>> _ = doc.rect(10, 10, 20, 20)
>>> doc.fit(padding=2).root.view_box
ViewBox(min_x=8.0, min_y=8.0, width=24.0, height=24.0)
What the code above draws
get_element_by_id(element_id: str) → Element | None

Find an element anywhere in the tree by its id.

Parameters:

element_id (str) – The id to look for.

Returns:

Element or None – The element, or None when no element has that id.

See also

__getitem__

doc["id"] raises instead of returning None.

Examples

>>> from svgwriter import Document
>>> doc = Document(10, 10)
>>> _ = doc.rect(0, 0, 5, 5, id="logo")
>>> doc.get_element_by_id("logo").tag, doc.get_element_by_id("none")
('rect', None)
What the code above draws
guide(x: float | None = None, y: float | None = None, *, angle: float | None = None, **kwargs: Any) → Guide

Add an Inkscape guide line and return it.

Parameters:
  • x (float, optional) – Give x alone for a vertical guide, y alone for a horizontal one, or both with angle for a slanted guide through that point.

  • y (float, optional) – Give x alone for a vertical guide, y alone for a horizontal one, or both with angle for a slanted guide through that point.

  • angle (float, optional) – Direction in degrees, clockwise from the x axis. Defaults to None, which follows from the coordinates given.

  • **kwargs – label, color or locked (see Guide).

Returns:

Guide – The new guide.

Raises:

TypeError – If neither x nor y is given.

Examples

>>> import svgwriter as svg
>>> doc = svg.Document(100, 100)
>>> doc.guide(x=50).angle, doc.guide(50, 50, angle=45).angle, len(doc.guides)
(90.0, 45, 2)
What the code above draws
property guides: list[Guide]

Inkscape’s guide lines, in user units; assign a list to replace them.

Examples

>>> import svgwriter as svg
>>> doc = svg.Document(100, 50)
>>> doc.guides = [svg.inkscape.Guide.vertical(25), svg.inkscape.Guide.horizontal(10, label="base")]
>>> [(g.x, g.y, g.angle) for g in doc.guides]
[(25.0, 0.0, 90.0), (0.0, 10.0, 0.0)]
What the code above draws
layer(label: str, **kwargs: Any) → Group

The Inkscape layer called label at the insertion point, added if missing.

Use it with with to draw into the layer; inside another layer it finds or adds a sublayer.

Parameters:
  • label (str) – The name shown in Inkscape’s Layers panel.

  • **kwargs – Attributes for a new layer’s <g>.

Returns:

Group – The existing or new layer.

See also

layers

Every layer by label.

Examples

>>> import svgwriter as svg
>>> doc = svg.Document(100, 100)
>>> with doc.layer("Background"):
...     _ = doc.rect(0, 0, 100, 100, fill="navy")
>>> doc.layer("Background") is doc.layers["Background"], len(doc.layers["Background"])
(True, 1)
What the code above draws
property layers: dict[str, Group]

Every layer and sublayer by label, in document order.

Examples

>>> import svgwriter as svg
>>> doc = svg.Document.from_string(
...     '<svg xmlns="http://www.w3.org/2000/svg" xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape">'
...     '<g inkscape:groupmode="layer" inkscape:label="Ink"/></svg>')
>>> list(doc.layers)
['Ink']
What the code above draws
nest(element: E) → Generator[E, None, None]

Add element and make it the insertion point inside the block.

Parameters:

element (Element) – The container to add and open.

Yields:

Element – The same element.

See also

add

Add without nesting.

Examples

>>> import svgwriter as svg
>>> doc = svg.Document(10, 10)
>>> with doc.nest(svg.Group()) as g:
...     _ = doc.circle(5, 5, 2)
>>> len(g)
1
What the code above draws
classmethod open(path: AnyPath, *, format: str | None = None, **options: Any) → Document

Read any registered input format (SVG, SVGZ, PNG, JPEG, …), chosen by extension.

Parameters:
  • path (str or os.PathLike) – The file to read.

  • format (str, optional) – Format name or extension. Defaults to None, which follows the extension of path.

  • **options – Loader options.

Returns:

Document – The loaded document.

Raises:

ValueError – If the options ask for every page (page=None); use open_all().

See also

from_string

Parse SVG text.

open_all

Every page or slide of a file.

Examples

>>> import tempfile, pathlib
>>> from svgwriter import Document
>>> with tempfile.TemporaryDirectory() as folder:
...     path = pathlib.Path(folder) / "a.svg"
...     Document(10, 10).save(path)
...     print(len(Document.open(path)))
0
classmethod open_all(path: AnyPath, *, format: str | None = None, **options: Any) → list[Document]

Read every page of a PDF, every slide of a PowerPoint deck, or the one drawing of other formats.

Parameters:
  • path (str or os.PathLike) – The file to read.

  • format (str, optional) – Format name or extension. Defaults to None, which follows the extension of path.

  • **options – Loader options other than the page choice.

Returns:

list of Document – One document per page or slide; a single-page format gives a list of one.

See also

open

Read one page.

svgwriter.formats.export.save

Writes a list of documents as pages or slides.

Examples

>>> import tempfile, pathlib
>>> import svgwriter as svg
>>> with tempfile.TemporaryDirectory() as folder:
...     path = svg.export.save([svg.Document(10, 10), svg.Document(20, 5)], pathlib.Path(folder) / "a.pdf")
...     [page.root.get("width") for page in svg.Document.open_all(path)]
[10.0, 20.0]
rasterize(*, scale: float = 1.0, pixels: tuple[int, int] | int | None = None, padding: float = 0.0, background: ColorLike | None = None, snapshot: bool = False) → np.ndarray

Render into a float32 RGBA array (see svgwriter.ops.rasterize()).

Parameters:
  • scale (float, optional) – Pixels per user unit. Defaults to 1.0.

  • pixels ((int, int) or int, optional) – Output size in pixels as (width, height), or one int for a square. Defaults to None, which uses the document size times scale.

  • padding (float, optional) – Margin around the content, in user units. Defaults to 0.0.

  • background (str, optional) – Background color. Defaults to None (transparent).

  • snapshot (bool, optional) – Render a copy of the tree. Defaults to False.

Returns:

numpy.ndarray – Array of shape (height, width, 4).

See also

render_png

Encode the result as PNG bytes.

Examples

>>> from svgwriter import Document, Rect
>>> doc = Document()
>>> _ = doc.circle(0, 0, 10)
>>> doc.rasterize(pixels=(64, 64), padding=2).shape
(64, 64, 4)
What the code above draws
render_animation(path: AnyPath, fps: float = 30.0, duration: float | None = None, renderer: Renderer | str | None = None, *, update: Update | None = None, ffmpeg: str | None = None) → FilePath

Render frames through renderer and encode them with ffmpeg.

See svgwriter.motion.video.render_animation() for the parameters. ffmpeg is located before any frame is rendered.

Parameters:
  • path (str or os.PathLike) – Output file; the extension picks the encoder.

  • fps (float, optional) – Frames per second. Defaults to 30.0.

  • duration (float, optional) – Seconds to render. Defaults to the end of the document’s SMIL animations.

  • renderer (callable or str, optional) – A renderer, a registered name such as "skia" or "module:function". Defaults to None, which raises; there is no default renderer.

  • update (callable, optional) – update(document, seconds) called before each frame. Defaults to None.

  • ffmpeg (str, optional) – The ffmpeg executable. Defaults to ffmpeg found on PATH.

Returns:

pathlib.Path – The written file.

Raises:

See also

svgwriter.motion.video.iter_frames

The frames without encoding.

Examples

>>> from svgwriter import Document, Rect
>>> doc = Document(8, 6)
>>> doc.render_animation("out.gif", duration=1, renderer="skia")
render_png(*, scale: float = 1.0, background: ColorLike | None = None) → bytes

Render to PNG bytes.

Parameters:
  • scale (float, optional) – Pixels per user unit. Defaults to 1.0.

  • background (str, optional) – Background color. Defaults to None (transparent).

Returns:

bytes – A PNG file.

See also

rasterize

The pixels without encoding.

Examples

>>> from svgwriter import Document, Rect
>>> doc = Document(8, 6)
>>> doc.render_png()[1:4]
b'PNG'
What the code above draws
save(target: AnyPath | TextSink, *, format: str | None = None, **options: Any) → None

Write to a path or text stream; the format follows format or the file extension.

.svg (and text streams) write SVG text with SerializeOptions; other extensions use svgwriter.formats.export (.png, .pdf, .tikz, …).

Parameters:
  • target (str, os.PathLike or TextSink) – Destination path or text stream.

  • format (str, optional) – Format name or extension. Defaults to None, which follows the extension of target, or SVG for streams.

  • **options – Serializer or exporter options.

See also

export

Return the output instead of writing it.

to_string

The SVG text.

Examples

>>> from svgwriter import Document, Rect
>>> doc = Document(10, 10)
>>> doc.save("figure.pdf")
What the code above draws
async save_async(path: str | PathLike[str], **options: Any) → None

Write the SVG text to path in a worker thread.

Parameters:

See also

save

The synchronous version.

Examples

>>> import asyncio, tempfile, pathlib
>>> from svgwriter import Document
>>> with tempfile.TemporaryDirectory() as folder:
...     path = pathlib.Path(folder) / "a.svg"
...     asyncio.run(Document(10, 10).save_async(path))
...     print(path.exists())
True
style(css: str | StyleSheet = '', **kwargs: Any) → StyleElement

Add a <style> sheet near the top of the document.

Parameters:
Returns:

StyleElement – The new element, placed after the <title> when there is one.

Examples

>>> import svgwriter as svg
>>> doc = svg.Document(10, 10)
>>> doc.style(".a { fill: red }").tag
'style'
What the code above draws
title(text: str) → Title

Add a <title> as the first child of the root.

Parameters:

text (str) – The accessible name of the document.

Returns:

Title – The new element.

See also

describe

Add a longer description.

Examples

>>> import svgwriter as svg
>>> doc = svg.Document(10, 10)
>>> doc.title("Chart").children
['Chart']
What the code above draws
to_string(**options: Any) → str

Serialize; see svgwriter.formats.io.SerializeOptions. Auto-sized documents get their size here.

Parameters:

**options – Fields of SerializeOptions.

Returns:

str – The SVG text.

See also

save

Write to a file or stream.

Examples

>>> from svgwriter import Document, Rect
>>> doc = Document(10, 10)
>>> _ = doc.circle(5, 5, 2)
>>> print(doc.to_string(pretty=False, xml_declaration=False))
<svg xmlns="http://www.w3.org/2000/svg" width="10" height="10" viewBox="0 0 10 10" version="1.1"><circle cx="5" cy="5" r="2"/></svg>
What the code above draws
used_faces(*typefaces: Typeface) → list[Face]

The faces the document’s text uses, one per font file.

Every text element’s font-family list (style sheets and theme roles included) is matched against the typefaces, and CSS font matching picks the face for its font-weight and font-style.

Parameters:

*typefaces (Typeface) – The families to look for. Defaults to every Typeface made in this session.

Returns:

list of Face – The faces in first-use order; variable faces keep their whole range.

See also

embed_fonts

Write these faces into the document.

Examples

>>> import svgwriter as svg
>>> serif = svg.Typeface("serif")
>>> doc = svg.Document(100, 40)
>>> _ = doc.text("Hi", x=0, y=20, font_family=serif)
>>> len(doc.used_faces(serif))
1
What the code above draws
wireframe(*, color: str = '#0ea5e9', width: float | None = None, bounds: bool = False) → Any

A copy drawn as thin outlines, to see the geometry under the paint (for debugging).

Parameters:
  • color (str, optional) – Outline colour. Defaults to sky blue.

  • width (float, optional) – Outline width in user units. Defaults to None: a hairline scaled to the drawing.

  • bounds (bool, optional) – Also draw each shape’s bounding box, dashed. Defaults to False.

Returns:

Document – The wireframe; this one is unchanged.

See also

svgwriter.ops.wireframe

The function behind it.

Examples

>>> import svgwriter as svg
>>> svg.Document(width=10, height=10).wireframe().root.get("fill") or "none"
'none'

Named sizes

Document(size="a4"), Scene.size and project files take a name or a PageSize from svg.size; svgwriter sizes lists the names. Paper and card sizes are in millimetres or inches, so the viewBox counts in those units; screen sizes are pixels. Append -landscape or -portrait to any name to turn it.

class PageSize(width: float, height: float, units: Unit = Unit.NONE)[source]

Bases: object

A canvas size: a width and a height counted in one unit.

Look the built-in ones up as attributes of svgwriter.size (svg.size.a4), add your own with svgwriter.library.preset.size, and pass either to Document(size=...), Scene.size or a project’s size.

Parameters:
  • width (float) – The two sides, in units.

  • height (float) – The two sides, in units.

  • units (Unit, optional) – The unit both sides are counted in. Defaults to Unit.NONE, user units (pixels).

See also

svgwriter.size

The built-in sizes by name.

svgwriter.library.preset.size

Register a size under a name.

Examples

>>> import svgwriter as svg
>>> a4 = svg.size.a4
>>> a4
PageSize(width=210.0, height=297.0, units=<Unit.MM: 'mm'>)
>>> str(a4.landscape), a4.landscape.portrait == a4
('297mm x 210mm', True)
>>> svg.Document(size=a4.landscape).root.get("viewBox").width
297.0
width: float
height: float
units: Unit
classmethod of(width: Length | float | int | str, height: Length | float | int | str) → PageSize[source]

A size from two lengths of one unit.

Parameters:
  • width (Length, float or str) – A Length, length text such as "50cm", or pixels.

  • height (Length, float or str) – A Length, length text such as "50cm", or pixels.

Returns:

PageSize – The size.

Raises:

ValueError – If the two lengths have different units.

Examples

>>> import svgwriter as svg
>>> svg.PageSize.of("50cm", "70cm")
PageSize(width=50.0, height=70.0, units=<Unit.CM: 'cm'>)
property lengths: tuple[Length, Length]

(width, height) as Length values.

property landscape: PageSize

The same size with the long side across.

property portrait: PageSize

The same size with the long side down.

size

svg.size.a4, svg.size.slide_16_9, svg.size.<your own>.

Type:

The registered sizes as attributes

page_size(size: str | PageSize) → tuple[Length, Length][source]

The width and height of a size, turned for a -landscape or -portrait suffix.

Parameters:

size (str or PageSize) – A PageSize, or a name from svg.preset.size.list() ("a4", "letter", "slide-16:9", "instagram-story", …), optionally followed by -landscape (long side across) or -portrait (long side down).

Returns:

tuple of Length – (width, height).

Raises:

UnknownNameError – If the name is unknown; the message suggests the closest names.

See also

svgwriter.library.preset.size

Add a size.

Examples

>>> import svgwriter as svg
>>> [str(side) for side in svg.page_size("a4-landscape")]
['297mm', '210mm']
>>> svg.page_size("a44")
Traceback (most recent call last):
...
svgwriter.errors.UnknownNameError: unknown size 'a44'; did you mean 'a4'? (svg.preset.size.list() lists every size)