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,ElementFactoryAn 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 withwith.- Parameters:
width (float or Length, optional) – Canvas size; a matching
viewBoxis 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
viewBoxis 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", … (seesize), with-landscapeor-portraitappended to turn it. Paper sizes are in millimetres or inches, so theviewBoxcounts 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 takesTheme.current()("light"outside awith 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.SvgThe root element wrapped by a document.
svgwriter.library.preset.sizeAdd 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)ordoc.defs += xdoes 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'
- 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 asopen().- Parameters:
text (str or bytes) – The source;
stris 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 onlytheme=, 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
openRead 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(aSerializeOptions) is used when saving.
- Yields:
Document – The document to draw into.
See also
saveSave 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]ordoc["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')
- __iter__() Iterator[Element]¶
Top-level content elements (
<defs>,<style>,<title>,<desc>skipped).Use
doc.root.iter()to walk the whole tree.
- 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
defineAdd 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
- 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_animationUses this for each frame, so SMIL plays without
update.
Notes
Supports
animate,set,animateColor,animateTransformandanimateMotionwith clock timing,repeatCount,repeatDur,fill="freeze",values/from/to/by,keyTimes, discrete mode andadditive="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'
- property auto_size: bool¶
Whether the canvas is computed from the content (no
width,heightorviewBoxset).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
fitApply 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)
- 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
- 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
addAdd 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)
- property defs: Defs¶
The root
<defs>, created on first use;doc.defs += xadds 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)
- describe(text: str) Desc¶
Add a
<desc>at the insertion point.- Parameters:
text (str) – The description.
- Returns:
Desc – The new element.
See also
titleAdd a short name.
Examples
>>> import svgwriter as svg >>> doc = svg.Document(10, 10) >>> doc.describe("A blue square").children ['A blue square']
- embed_fonts(*typefaces: Typeface) StyleElement | None¶
Add
@font-facerules 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
Typefacemade in this session.- Returns:
StyleElement or None – The new
<style>, or None when no text uses the typefaces.
See also
used_facesThe faces that would be written.
Typeface.cssThe 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
- 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
saveWrite 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 noscale,dpiorsizeis 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)
- fit(padding: float = 0.0) Self¶
Set
viewBox,widthandheightto the content bounds (plus padding) and returnself.- Parameters:
padding (float, optional) – Margin added on every side. Defaults to 0.0.
- Returns:
Document – This document, for chaining.
See also
content_boundsThe 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)
- 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)
- 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,colororlocked(seeGuide).
- 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)
- 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)]
- layer(label: str, **kwargs: Any) Group¶
The Inkscape layer called label at the insertion point, added if missing.
Use it with
withto 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
layersEvery 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)
- 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']
- 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
addAdd 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
- 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); useopen_all().
See also
from_stringParse SVG text.
open_allEvery 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
openRead one page.
svgwriter.formats.export.saveWrites 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_pngEncode 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)
- 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
ffmpegfound onPATH.
- Returns:
pathlib.Path – The written file.
- Raises:
FFmpegNotFoundError – When ffmpeg is missing.
FFmpegError – When ffmpeg fails.
See also
svgwriter.motion.video.iter_framesThe 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:
- Returns:
bytes – A PNG file.
See also
rasterizeThe pixels without encoding.
Examples
>>> from svgwriter import Document, Rect >>> doc = Document(8, 6) >>> doc.render_png()[1:4] b'PNG'
- 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 withSerializeOptions; other extensions usesvgwriter.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.
Examples
>>> from svgwriter import Document, Rect >>> doc = Document(10, 10) >>> doc.save("figure.pdf")
- async save_async(path: str | PathLike[str], **options: Any) None¶
Write the SVG text to path in a worker thread.
- Parameters:
path (str or os.PathLike) – Destination file.
**options –
optionsor fields ofSerializeOptions.
See also
saveThe 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:
css (str or StyleSheet, optional) – The stylesheet. Defaults to an empty string.
**kwargs – Forwarded to
StyleElement.
- 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'
- 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
describeAdd a longer description.
Examples
>>> import svgwriter as svg >>> doc = svg.Document(10, 10) >>> doc.title("Chart").children ['Chart']
- 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
saveWrite 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>
- used_faces(*typefaces: Typeface) list[Face]¶
The faces the document’s text uses, one per font file.
Every text element’s
font-familylist (style sheets and theme roles included) is matched against the typefaces, and CSS font matching picks the face for itsfont-weightandfont-style.- Parameters:
*typefaces (Typeface) – The families to look for. Defaults to every
Typefacemade in this session.- Returns:
list of Face – The faces in first-use order; variable faces keep their whole range.
See also
embed_fontsWrite 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
- 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:
- Returns:
Document – The wireframe; this one is unchanged.
See also
svgwriter.ops.wireframeThe 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:
objectA 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 withsvgwriter.library.preset.size, and pass either toDocument(size=...),Scene.sizeor a project’ssize.- Parameters:
See also
svgwriter.sizeThe built-in sizes by name.
svgwriter.library.preset.sizeRegister 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
- classmethod of(width: Length | float | int | str, height: Length | float | int | str) PageSize[source]¶
A size from two lengths of one unit.
- Parameters:
- 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'>)
- 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
-landscapeor-portraitsuffix.- Parameters:
size (str or PageSize) – A
PageSize, or a name fromsvg.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.sizeAdd 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)