SVG

The SVG module generates tags inside <svg> tags. It does not generate a doctype, or XML/HTML wrappers. The default extension is ‘.svg’ but you will need to write appropriate info outside of the script block. The simplest wrapper to use is HTML5, where all that is required to embed the SVG tags in a minimal html doc, no doctype required!

>>> from pygencad import *
>>> from StringIO import StringIO
>>> f = StringIO()
>>> f.write("<html><head></head><body>\n")
>>> with get_script(f, 'svg') as script:
...     with script.layer('hello'):
...         hello = script.cmd('hello')
...         hello.text = "Hello, World!"
...
>>> f.write("\n</body></html>")
>>> print f.getvalue() 
<html><head></head><body>
<svg ...><g ...><hello class="hello">Hello, World!</hello><style>
<![CDATA[
    line, polyline, circle {
        stroke: black;
        fill: none;
        stroke-width: 0.1px;
    }
    .hello {
            stroke: black;
            stroke-width: 0.1;
            stroke-dasharray: 0;
    }
]]>
</style></g></svg>
</body></html>

Backend that outputs to SVG tags.

SVG is generated using the ‘xml.etree’ ElementTree std. lib module. A write parameter has been added to all geometry creation methods, and all methods return any ELementTree.Elements created.

Note

If the svg.CommandFile isn’t used as a context manager you will have to provide a root ElementTree.Element using CommandFile.set_root method. Also you will need to call CommandFile.teardown manually to add the style block to the root, and write the tree to the provided file object.

Warning

The point, points, and reset methods have no meaningful representation in SVG. Any script using these methods cannot be run against the SVG backend.

There are several special module attributes:

attr WIDTH:SVG doc width.
attr HEIGHT:SVG doc height.
attr FACTOR:The initial scale factor of the drawing.
attr NAVIGATE:Toggles inclusion of SVGPan.js in teardown.

WIDTH and HEIGHT are written in the <svg> tag as their respective attributes. The viewbox is set to ‘0 0 WIDTH HEIGHT’ to match display and drawing units.

To better match other CAD packages a group is added inside the SVG tag wrapping all other elements that mirrors everything across the y-axis so positive y is up, and everything is translated down by HEIGHT so that the origin is in the bottom left corner. This is also where initial scale FACTOR is applied.

classes

Layer

class pygencad.svg.Layer(name, co=None, lw=None, lc=None)[source]

Group objects with identical styles.

Note

All layers have a fill style of none.

Parameters:
  • name (string OR Layer-like) – This is the class name for the layer style. A tuple of layer properties, or a Layer object may be passed as the first argument (name) in which case the new layer is initialized with provided values.
  • co – The color of the layer [default: black].
  • lw – The line-weight of the layer [default: 0.1].
  • lc – The line-class (type) of the layer. The line-class can be None for continuous lines, one of the names in the Layer.linecls class attribute, or an iterable of ints.

Store properties and setup template.

linecls = {'phantom': (0.75, 0.2, 0.2, 0.2, 0.2, 0.2), 'hidden': (0.25, 0.2), 'continuous': (0,), 'center': (1, 0.2, 0.2, 0.2)}

Named line classes

colors = {1: 'red', 2: 'yellow', 3: 'green', 4: 'cyan', 5: 'blue', 6: 'magenta', 7: 'black', 8: 'gray', 9: 'lightgray'}

Indexed colors

__str__()[source]

Render this layer as a CSS style.

CommandFile

class pygencad.svg.CommandFile(filelike, setup=None, teardown=None)[source]

Wrapper for SVG generation.

Convenience methods for building an SVG tree and writing it to a filelike.

Parameters:
  • filelike (filelike) – An object with a write method.
  • setup (callable OR valid CommandFile.cmd argument) – Commands to include at the beginning of the script.
  • teardown (callable OR valid CommandFile.cmd argument) – Commands to include at the end of the script.
class Layer(name, co=None, lw=None, lc=None)

A local binding to the SVG Layer class

CommandFile.set_root(el, transform=False)[source]

Sets the ElementTree Element to which tags will be added.

Also adds a wrapper group that modifies the SVG coordinate system.

Parameters:el (ElementTree.Element) – The element to set as root.
Raises:TypeError if el doesn’t pass ElementTree.iselement test.
CommandFile.setup()[source]

Add default configuration info and run user provided setup func.

Called automatically by CommandFile context manager. Writes default setup code, then adds any user provided setup. If the user setup is callable the return value is written to the script, otherwise the user setup is written as a string.

Note

User setup is handled differently in SVG, if the user setup is not a function it is passed to the cmd method to be added as a tag.

CommandFile.teardown()[source]

Add final tags, run user provided teardown func, and write filelike.

Called automatically by CommandFile context manager. Writes any user provided teardown, then writes default teardown code. If the user teardown is callable the return value is written to the script, otherwise the user teardown is written as a string.

Note

User teardown is handled differently in SVG, if the user teardown is not a function it is passed to the cmd method to be added as a tag.

CommandFile.set_layer(layer, *args, **kwargs)[source]

Activates the provided layer object or description.

Parameters:
  • layer – A layer object, or a valid Layer name argument.
  • *args – Valid Layer arguments.
  • **kwargs – Valid Layer arguments.
CommandFile.pop_layer()[source]

Restores active layer prior to last set_layer call.

CommandFile.cmd(command, *args, **kwargs)[source]

Add arbitrary elements to script root.

The command argument is expected to be a tag name, or an ElementTree.Element, or an iterable of ElementTree Elements. If command is a string then *args and **kwargs are passed to the Element init. if command is already an element then the extra args are ignored.

Parameters:
  • command (string OR ElementTree.Element OR Element iterable) – The element(s) to be added to the document.
  • *args (dict) – The attrib argument of ElementTree.Element.
  • **kwargs – Extra attributes for the new ElementTree.Element.
  • write (boolean) – Whether the element should be added to root (default=True).
Returns:

Element

CommandFile.line(ps, reset=False, mode=None, write=True)[source]

Add a series of line segment tags to root.

Since the SVG line tag only supports a single line segment multiple tags may be added to a single set of points.

Parameters:
  • ps – The end points of the lines.
  • reset (boolean) – Unused in SVG backend.
  • mode (string) – Unimplemented, relative coordinates could be implemented for individual method invocations.
  • write (boolean) – Whether the line elements should be added to root.
Returns:

Element list

CommandFile.polyline(ps, close=True, reset=False, mode=None, write=True)[source]

Add a polyline tag to root.

Points are written as “x,y” pairs seperated by spaces, so splitting produces point strings, and splitting those strings on ‘,’ produces the point components.

Parameters:
  • ps – The ordered points forming the line.
  • close (boolean) – Flag indicating whether the line should end where it started.
  • reset (boolean) – Unused in SVG backend.
  • mode (string) – Unimplemented, relative coordinates could be implemented for individual method invocations.
  • write (boolean) – Whether the element should be added to root.
Returns:

Element

CommandFile.circle(center, radius, write=True)[source]

Add a circle tag to root.

Parameters:
  • center (iterable) – The center of the circle.
  • radius (number) – The radius of the circle.
  • write (boolean) – Whether the element should be added to root.
Returns:

Element

CommandFile.text(text, p, height=1.0, ang=0, just='tl', write=True)[source]

Add a text tag to root.

The text is inspected for newline chars, and <tspan> tags are added with (hopefully) appropriate dx/dy values to create multiline text.

Parameters:
  • text (string) – The text to place.
  • p (iterable) – The insertion point in a format passable to CommandFile.point.
  • height (number) – How tall the text lines are.
  • ang (number) – The angle of the text in degrees.
  • just (string) – The justification of the text, a pair of [t, m, b][l, c, r].
  • write (boolean) – Whether the element should be added to root.
Returns:

Element

CommandFile.store(name, *els)[source]

Store provided elements to be manipulated later.

This method is provided as a uniform interface for grouping objects regardless of backend. In the SVG backend this is a noop.

Parameters:
  • name (Unused) – The id used to store the selection.
  • *els (SVG elements or element lists.) – The elements to store.
Raises:

ValueError if no elements are provided.

Returns:

An element group passable to move/copy/rotate/scale methods.

CommandFile.move(els, base=(0, 0), dest=(0, 0))[source]

Transform the provided elements from base to dest.

Parameters:
  • els (iterable of Elements) – The elements to move.
  • base (iterable) – The base point to transform from.
  • dest (iterable) – The dest point to transform to.
Returns:

Element list

CommandFile.copy(els, base=(0, 0), dest=(0, 0), write=True)[source]

Transform duplicates of the provided elements from base to dest.

Parameters:
  • els (iterable of Elements) – The elements to copy.
  • base (iterable) – The base point to transform from.
  • dest (iterable) – The dest point to transform to.
  • write (boolean) – Whether the elements should be added to root.
Returns:

Element list

CommandFile.rotate(els, base=(0, 0), ang=0)[source]

Rotate the provided elements from base by angle.

Parameters:
  • els (iterable of Elements) – The elements to rotate.
  • base (iterable) – The base point to transform from.
  • ang (number) – The angle to rotate in degrees (counter-clockwise).
Returns:

Element list

CommandFile.scale(els, base=(0, 0), scale=(1, 1))[source]

Scale the provided elements from base by scale.

Remember that scaling an axis by -1 is equivalent to mirroring.

Parameters:
  • els (iterable of Elements) – The elements to scale.
  • base (iterable) – The base point to transform from.
  • scale (iterable) – The x and y scale factor to apply.
Returns:

Element list

CommandFile.erase(els)[source]

Remove the indicated elements from root.

Parameters:els (iterable of Elements) – The elements to remove.
Returns:Element list
CommandFile.layer(*args, **kwds)[source]

Script layer context manager.

Activates the provided layer settings, and resets layer state on exit.

>>> from pygencad.commandfile import CommandFile
>>> from StringIO import StringIO
>>> f = StringIO()
>>> with CommandFile(f) as script:
...     with script.layer('layer'):
...         script.cmd("test")
... 
'l'
>>> print f.getvalue() 
Layer:
    lv=layer
    co=None
    lw=None
    lc=None
test
Parameters:
  • *args – Valid Layer arguments.
  • **kwargs – Valid Layer arguments.