inkex package

Submodules

inkex.base module

The ultimate base functionality for every inkscape extension.

class inkex.base.InkscapeExtension[source]

Bases: object

The base class extension, provides argument parsing and basic variable handling features.

absolute_href(filename, default='~/')[source]

Process the filename such that it’s turned into an absolute filename with the working directory being the directory of the loaded svg.

User’s home folder is also resolved. So ‘~/a.png` will be /home/bob/a.png

Default is a fallback directory to use if the svg’s filename is not available.

add_arguments(pars)[source]

Add any extra arguments to your extension handle, use:

def add_arguments(self, pars):
pars.add_argument(“–num-cool-things”, type=int, default=3) pars.add_argument(“–pos-in-doc”, type=str, default=”doobry”)
arg_method(prefix='method')[source]

Used by add_argument to match a tab selection with an object method

pars.add_argument(“–tab”, type=self.arg_method(), default=”foo”) … self.otpions.tab(arguments) … def method_foo(self, arguments):

# do something
clean_up()[source]

Clean up any open handles and other items

debug(msg)[source]

Write a debug message

effect()[source]

Apply some effects on the document or local context

classmethod ext_path()[source]

Return the folder the extension script is in

has_changed(ret)[source]

Return true if the output should be saved

load(stream)[source]

Takes the input stream and creates a document for parsing

load_raw()[source]

Load the input stream or filename, save everything to self

static msg(msg)[source]

Write a non-error message

multi_inx = False
name

Return a fixed name for this extension

parse_arguments(args)[source]

Parse the given arguments and set ‘self.options’

run(args=None, output=None)[source]

Main entrypoint for any Inkscape Extension

save(stream)[source]

Save the given document to the output file

save_raw(ret)[source]

Save to the output steam, use everything from self

svg_path()[source]

Return the folder the svg is contained in. Returns None if there is no file.

class inkex.base.SvgInputMixin[source]

Bases: object

Expects the file input to be an svg document and will parse it.

load(stream)[source]

Load the stream as an svg xml etree and make a backup

class inkex.base.SvgOutputMixin[source]

Bases: object

Expects the output document to be an svg document and will write an etree xml.

A template can be specified to kick off the svg document building process.

classmethod get_template(**kwargs)[source]

Opens a template svg document for building, the kwargs MUST include all the replacement values in the template, the default template has ‘width’ and ‘height’ of the document.

save(stream)[source]

Save the svg document to the given stream

template = '<svg viewBox="0 0 {width} {height}" width="{width}{unit}" height="{height}{unit}"\n xmlns="http://www.w3.org/2000/svg" xmlns:svg="http://www.w3.org/2000/svg"\n xmlns:xlink="http://www.w3.org/1999/xlink"\n xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd"\n xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape">\n </svg>'
class inkex.base.SvgThroughMixin[source]

Bases: inkex.base.SvgInputMixin, inkex.base.SvgOutputMixin

Combine the input and output svg document handling (usually for effects.

has_changed(ret)[source]

Return true if the svg document has changed

class inkex.base.TempDirMixin(*args, **kwargs)[source]

Bases: object

Provide a temporary directory for extensions to stash files.

clean_up()[source]

Delete the temporary directory

dir_prefix = 'inktmp'
dir_suffix = ''
load_raw()[source]

Create the temporary directory

inkex.bezier module

Bezier calculations

inkex.bezier.addifclose(bez, l, error=0.001)[source]

Gravesen, Add if the line is closed, in-place addition to array l

inkex.bezier.balf(t, args)[source]

Bezier Arc Length Function

inkex.bezier.between_point(point_a, point_b, time=0.5)[source]

Returns the point between point a and point b

inkex.bezier.bezierlength(bez, tolerance=0.001, time=1.0)[source]

Get length of bezier curve

inkex.bezier.bezierparameterize(bez)[source]

Return the bezier parameter size

inkex.bezier.bezierpointatt(bez, t)[source]

Get coords at the given time point along a bezier curve

inkex.bezier.bezierslopeatt(bez, t)[source]

Get sloap at the given time point along a bezier curve

inkex.bezier.beziersplitatt(bez, t)[source]

Split bezier at given time

inkex.bezier.beziertatlength(bez, l=0.5, tolerance=0.001)[source]

Get bezier curve time at the length specified

inkex.bezier.beziertatslope(bez, d)[source]

Reverse; get time from sloap along a bezier curve

inkex.bezier.bezlenapprx(sp1, sp2)[source]

Return the aproximate length between two beziers

inkex.bezier.csparea(csp)[source]

Get area in cubic sub-path

inkex.bezier.cspbezsplit(sp1, sp2, time=0.5)[source]

Split a cubic bezier at the time period

inkex.bezier.cspbezsplitatlength(sp1, sp2, length=0.5, tolerance=0.001)[source]

Split a cubic bezier at length

inkex.bezier.cspcofm(csp)[source]

Get cubic sub-path coefficient

inkex.bezier.csplength(csp)[source]

Get cubic bezier length

inkex.bezier.cspseglength(sp1, sp2, tolerance=0.001)[source]

Get cubic bezier segment length

inkex.bezier.cspsubdiv(csp, flat)[source]

Sub-divide cubic sub-paths

inkex.bezier.linebezierintersect(arg_a, bez)[source]

Where a line and bezier intersect

inkex.bezier.maxdist(bez)[source]

Get maximum distance within bezier curve

inkex.bezier.percent_point(point_a, point_b, percent=50.0)[source]

Returns between_point but takes percent instead of 0.0-1.0

inkex.bezier.pointdistance(point_a, point_b)[source]

The size of the line between two points

inkex.bezier.root_wrapper(root_a, root_b, root_c, root_d)[source]

Get the Cubic function, moic formular of roots, simple root

inkex.bezier.simpson(a, b, n_limit, tolerance, balarg)[source]

It’s not known what this function does…

inkex.bezier.subdiv(sp, flat, i=1)[source]

sub divide bezier curve

inkex.bezier.tpoint(p1, p2, t)[source]

Linearly interpolate between p1 and p2.

t = 0.0 returns p1, t = 1.0 returns p2.

Returns:

Interpolated point

Return type:

tuple

Parameters:
  • p1 – First point as sequence of two floats
  • p2 – Second point as sequence of two floats
  • t (float) – Number between 0.0 and 1.0

inkex.colors module

Basic color controls

class inkex.colors.Color(color=None, space='rgb')[source]

Bases: list

An RGB array for the color

alpha
append(val)[source]

Append a value to the local list

blue
green
hue
lightness
static parse_int(color)[source]

Creates an rgb or rgba from a long int

static parse_str(color)[source]

Creates a rgb int array

red
saturation
to(space)[source]

Dynamic caller for to_hsl, to_rgb, etc

to_floats()[source]

Returns the colour values as percentage floats (0.0 - 1.0)

to_hsl()[source]

Turn this color into a Hue/Saturation/Lightness colour space

to_named()[source]

Convert this color to a named color if possible

to_rgb()[source]

Turn this color into a Red/Green/Blue colour space

to_rgba(alpha=1.0)[source]

Turn this color isn’t an RGB with Alpha colour space

exception inkex.colors.ColorError[source]

Bases: KeyError

Specific color parsing error

exception inkex.colors.ColorIdError[source]

Bases: inkex.colors.ColorError

Special color error for gradient and color stop ids

inkex.command module

This API provides methods for calling Inkscape to execute a given Inkscape command. This may be needed for various compiling options (e.g., png), running other extensions or performing other options only available via the shell API.

Best practice is to avoid using this API except when absolutely necessary, since it is resource-intensive to invoke a new Inkscape instance.

However, in any circumstance when it is necessary to call Inkscape, it is strongly recommended that you do so through this API (rather than calling it yourself) to take advantage of the security settings and testing functions.

exception inkex.command.CommandNotFound[source]

Bases: OSError

Command is not found

exception inkex.command.ProgramRunError[source]

Bases: ValueError

Command returned non-zero output

inkex.command.call(program, *args, **kwargs)[source]

Generic caller to open any program and return its stdout.

stdout = call(‘executable’, arg1, arg2, dash_dash_arg=’foo’, d=True, …)

Will raise ProgramRunError() if return code is not 0.

inkex.command.inkscape(svg_file, *args, **kwargs)[source]

Call Inkscape with the given svg_file and the given arguments

inkex.command.inkscape_command(svg, select=None, verbs=())[source]

Executes a list of commands, a mixture of verbs, selects etc.

inkscape_command(‘<svg…>’, (‘verb’, ‘VerbName’), …)

inkex.command.is_inkscape_available()[source]

Return true if the inkscape executable is available.

inkex.command.take_snapshot(svg, dirname, name='snapshot', ext='png', dpi=96, **kwargs)[source]

Take a snapshot of the given svg file.

Resulting filename is yielded back, after generator finishes, the file is deleted so you must deal with the file inside the for loop.

inkex.command.to_arg(arg, oldie=False)[source]

Convert a python argument to a command line argument

inkex.command.to_args(prog, *positionals, **arguments)[source]

Convert positional arguments and key word arguments into a list of strings which Popen will understand.

Values can be:

args = *[
‘strait_up_string’, ‘–or_manual_kwarg=1’, (‘ordered list’, ‘version of kwargs (as below)’), …

] kwargs = **{

‘name’: ‘val’, # –name=”val”’ ‘name’: [‘foo’, ‘bar’], # –name=foo –name=bar ‘name’: True, # –name ‘n’: ‘v’, # -n=v ‘n’: True, # -n

}

All args appear after the kwargs, so if you need args before, use the ordered list tuple and don’t use kwargs.

inkex.command.which(program)[source]

Attempt different methods of trying to find if the program exists.

inkex.command.write_svg(svg, *filename)[source]

Writes an svg to the given filename

inkex.deprecated module

Provide some documentation to existing extensions about why they’re failing.

class inkex.deprecated.DeprecatedDict[source]

Bases: dict

class inkex.deprecated.DeprecatedEffect[source]

Bases: object

An Inkscape effect, takes SVG in and outputs SVG, providing a deprecated layer

OptionParser
addDocumentUnit(value)[source]
add_option(*args, **kw)[source]
affect(args=['build_sphinx', '-s', 'source'], output=True)[source]
args
createGuide(posX, posY, angle)[source]
current_layer
doc_ids
effect()[source]
getDocumentHeight()[source]
getDocumentUnit()[source]
getDocumentWidth()[source]
getElementById(eid)[source]
getNamedView()[source]
getParentNode(node)[source]
getdocids()[source]
getselected()[source]
save_raw(ret)[source]
selected
svg_file
uniqueId(old_id, make_new_id=True)[source]
unittouu(string)[source]
uutounit(val, unit)[source]
view_center
xpathSingle(xpath)[source]
class inkex.deprecated.Effect[source]

Bases: inkex.base.SvgThroughMixin, inkex.deprecated.DeprecatedEffect, inkex.base.InkscapeExtension

An Inkscape effect, takes SVG in and outputs SVG

inkex.deprecated.are_near_relative(a, b, eps)[source]
inkex.deprecated.debug(what)[source]
inkex.deprecated.deprecate(func)[source]

Function decorator for deprecation functions which have a one-liner equivalent in the new API. The one-liner has to passed as a string to the decorator.

>>> @deprecate
>>> def someOldFunction(*args):
>>>     '''Example replacement code someNewFunction('foo', ...)'''
>>>     someNewFunction('foo', *args)

Or if the args API is the same:

>>> someOldFunction = deprecate(someNewFunction)
inkex.deprecated.ensure_value(self, attr, value)[source]
class inkex.deprecated.lazyproxy(getwrapped)[source]

Bases: object

Proxy, use as decorator on a function with provides the wrapped object. The decorated function is called when a member is accessed on the proxy.

inkex.deprecated.localize[source]

Proxy, use as decorator on a function with provides the wrapped object. The decorated function is called when a member is accessed on the proxy.

inkex.deprecated.unittouu(string)[source]
inkex.deprecated.zSort(*args, **kwargs)[source]

Deprecated -> self.svg.get_z_selected()

inkex.extensions module

A helper module for creating Inkscape effect extensions

This provides the basic generic types of extensions which most writers should use in their code. See below for the different types.

class inkex.extensions.EffectExtension[source]

Bases: inkex.base.SvgThroughMixin, inkex.base.InkscapeExtension

Takes the SVG from Inkscape, modifies the selection or the document and returns an SVG to Inkscape.

class inkex.extensions.GenerateExtension[source]

Bases: inkex.extensions.EffectExtension

Does not need any SVG, but instead just outputs an SVG fragment which is inserted into Inkscape, centered on the selection.

container_label = ''
container_layer = False
container_transform()[source]

Generate the transformation for the container group, the default is to return the center position of the svg document or view port.

effect()[source]
generate()[source]

Return an SVG fragment to be inserted into the selected layer of the document OR yield multiple elements which will be grouped into a container Group element which will be given an automatic label and transformation.

class inkex.extensions.InputExtension[source]

Bases: inkex.base.SvgOutputMixin, inkex.base.InkscapeExtension

Takes any type of file as input and outputs SVG which Inkscape can read.

Used in functions for Open

effect()[source]

Effect isn’t needed for a lot of Input extensions

load(stream)[source]

But load certainly is, we give a more exact message here

class inkex.extensions.OutputExtension[source]

Bases: inkex.base.SvgInputMixin, inkex.base.InkscapeExtension

Takes the SVG from Inkscape and outputs it to something that’s not an SVG.

Used in functions for Save As

effect()[source]

Effect isn’t needed for a lot of Output extensions

save(stream)[source]

But save certainly is, we give a more exact message here

class inkex.extensions.CallExtension(*args, **kwargs)[source]

Bases: inkex.base.TempDirMixin, inkex.extensions.InputExtension

Call an external program to get the output

call(input_file, output_file)[source]

Call whatever programs are needed to get the desired result.

input_ext = 'svg'
load(stream)[source]
load_raw()[source]
output_ext = 'svg'
class inkex.extensions.TemplateExtension[source]

Bases: inkex.extensions.EffectExtension

Provide a standard way of creating templates.

arg_size(unit='px')[source]

Argument is a string of the form X[unit]xY[unit], default units apply when missing

effect()[source]

Creates a template, do not over-ride

get_size()[source]

Get the size of the new template (defaults to size options)

get_template()[source]

Can be over-ridden with custom svg loading here

set_namedview(width, height, unit)[source]

Setup the document namedview

size_rex = re.compile('([\\d.]*)(\\w\\w)?x([\\d.]*)(\\w\\w)?')
template_id = 'SVGRoot'
class inkex.extensions.ColorExtension[source]

Bases: inkex.extensions.EffectExtension

A standard way to modify colours in an svg document.

effect()[source]
modify_color(name, color)[source]

Replace this method with your colour modifier method

modify_opacity(name, opacity)[source]

Optional opacity modification

process_element(elem, gradients=None)[source]

Process one of the selected elements

process_elements(elem)[source]

Process multiple elements (gradients)

process_none = False
class inkex.extensions.TextExtension[source]

Bases: inkex.extensions.EffectExtension

A base effect for changing text in a document.

effect()[source]
static map_char(char)[source]

Replaceable map_char method for processing each letter

newline = True
newpar = True
process_chardata(text)[source]

Replaceable chardata method for processing the text

process_element(node)[source]

Reverse the node text

inkex.inx module

Parsing inx files for checking and generating.

class inkex.inx.InxFile(filename)[source]

Bases: object

Open an INX file and provide useful functions

extension_class

Attempt to get the extension class

find_one(name)[source]

Return the first element matching the given name

ident
kind
menu

Return the menu this effect ends up in

metadata

Returns information about what type of extension this is

name
params

Get all params at all levels

script

Returns information about the called script

slug
xpath(xpath)[source]

Namespace specific xpath searches

class inkex.inx.InxLookup[source]

Bases: lxml.etree.CustomElementClassLookup

Custom inx xml file lookup

lookup(node_type, document, namespace, name)[source]
class inkex.inx.ParamElement[source]

Bases: lxml.etree.ElementBase

A param in an inx file.

name
options

Return a list of option values

param_type

inkex.localization module

Allow extensions to translate messages.

inkex.localization.inkex_localize()[source]

Return internal Translations instance for translation of the inkex module itself Those will always use the ‘inkscape’ domain and attempt to lookup the same catalog Inkscape uses

inkex.localization.localize(domain=None, localedir=None)[source]

Configure gettext and install _() function into builtins namespace for easy access

inkex.paths module

functions for digesting paths into a simple list structure

class inkex.paths.Path(path_d=None)[source]

Bases: list

A list of segment commands which combine to draw a shape

class PathCommandProxy(command, first_point, previous_end_point, prev2_control_point)[source]

Bases: object

A handy class for Path traverse and coordinate access

Reduces number of arguments in user code compared to bare PathCommand methods

args
control_points
end_point
is_absolute
is_relative
letter
name
next_command
to_curve()[source]
to_curves()[source]
append(cmd)[source]

Append a command to this path including any chained commands

bounding_box()[source]

Return bounding box of the Path

close()[source]

Attempt to close the last path segment

control_points
copy()[source]

Make a copy

end_points
classmethod parse_string(path_d)[source]

Parse a path string and generate segment objects

proxy_iterator()[source]

Yields AugmentedPathIterator

Return type:Iterator[ Path.PathCommandProxy ]
reverse()[source]

Returns a reversed path

rotate(deg, center=None, inplace=False)[source]

Rotate the path around the given point

scale(x, y, inplace=False)[source]

Scale all coords in this path by the given amounts

to_absolute()[source]

Convert this path to use only absolute coordinates

to_arrays()[source]

Returns path in format of parsePath output, returning arrays of absolute command data

Deprecated since version 1.0: This is compatibility function for older API. Should not be used in new code

to_relative()[source]

Convert this path to use only relative coordinates

to_superpath()[source]

Convert this path into a cubic super path

transform(transform, inplace=False)[source]

Convert to new path

translate(x, y, inplace=False)[source]

Move all coords in this path by the given amount

class inkex.paths.CubicSuperPath(items)[source]

Bases: list

A conversion of a path into a predictable list of cubic curves which can be operated on as a list of simplified instructions.

When converting back into a path, all lines, arcs etc will be coverted to curve instructions.

Structure is held as [SubPath[(point_a, bezier, point_b), …]], …]

append(item)[source]

Accept multiple different formats for the data

static is_line(previous, segment)[source]

Check whether csp segment (two points) has retracted handles.

to_path(curves_only=False)[source]

Convert the super path back to an svg path

to_segments(curves_only=False)[source]

Generate a set of segments for this cubic super path

transform(transform)[source]

Apply a transformation matrix to this super path

class inkex.paths.Line(x, y)[source]

Bases: inkex.paths.AbsolutePathCommand

Line segment

args
control_points(first, prev, prev_prev)[source]
end_point(first, prev)[source]
nargs = 2
to_curve(prev, prev_prev=Vector2d(0, 0))[source]
to_relative(prev)[source]
transform(transform)[source]
update_bounding_box(first, last_two_points, bbox)[source]
class inkex.paths.line(dx, dy)[source]

Bases: inkex.paths.RelativePathCommand

Relative line segment

args
nargs = 2
to_absolute(prev)[source]
class inkex.paths.Move(x, y)[source]

Bases: inkex.paths.AbsolutePathCommand

Move pen segment without a line

args
control_points(first, prev, prev_prev)[source]
end_point(first, prev)[source]
nargs = 2
next_command

alias of Line

to_curve(prev, prev_prev=Vector2d(0, 0))[source]
to_relative(prev)[source]
transform(transform)[source]
update_bounding_box(first, last_two_points, bbox)[source]
class inkex.paths.move(dx, dy)[source]

Bases: inkex.paths.RelativePathCommand

Relative move segment

args
nargs = 2
next_command

alias of line

to_absolute(prev)[source]
class inkex.paths.ZoneClose[source]

Bases: inkex.paths.AbsolutePathCommand

Close segment to finish a path

args
control_points(first, prev, prev_prev)[source]
end_point(first, prev)[source]
nargs = 0
next_command

alias of Move

to_curve(prev, prev_prev=Vector2d(0, 0))[source]
to_relative(prev)[source]
transform(transform)[source]
update_bounding_box(first, last_two_points, bbox)[source]
class inkex.paths.zoneClose[source]

Bases: inkex.paths.RelativePathCommand

Same as above (svg says no difference)

args
nargs = 0
next_command

alias of Move

to_absolute(prev)[source]
class inkex.paths.Horz(x)[source]

Bases: inkex.paths.AbsolutePathCommand

Horizontal Line segment

args
control_points(first, prev, prev_prev)[source]
end_point(first, prev)[source]
nargs = 1
to_curve(prev, prev_prev=Vector2d(0, 0))[source]

Convert a horizontal line into a curve

to_line(prev)[source]

Return this path command as a Line instead

to_relative(prev)[source]
transform(transformation)[source]
update_bounding_box(first, last_two_points, bbox)[source]
class inkex.paths.horz(dx)[source]

Bases: inkex.paths.RelativePathCommand

Relative horz line segment

args
nargs = 1
to_absolute(prev)[source]
to_line(prev)[source]

Return this path command as a Line instead

class inkex.paths.Vert(y)[source]

Bases: inkex.paths.AbsolutePathCommand

Vertical Line segment

args
control_points(first, prev, prev_prev)[source]
end_point(first, prev)[source]
nargs = 1
to_curve(prev, prev_prev=Vector2d(0, 0))[source]

Convert a horizontal line into a curve

to_line(prev)[source]

Return this path command as a line instead

to_relative(prev)[source]
transform(transform)[source]
update_bounding_box(first, last_two_points, bbox)[source]
class inkex.paths.vert(dy)[source]

Bases: inkex.paths.RelativePathCommand

Relative vertical line segment

args
nargs = 1
to_absolute(prev)[source]
to_line(prev)[source]

Return this path command as a line instead

class inkex.paths.Curve(x2, y2, x3, y3, x4, y4)[source]

Bases: inkex.paths.AbsolutePathCommand

Absolute Curved Line segment

args
control_points(first, prev, prev_prev)[source]
end_point(first, prev)[source]
nargs = 6
to_bez()[source]

Returns the list of coords for SuperPath

to_curve(prev, prev_prev=Vector2d(0, 0))[source]

No conversion needed, pass-through, returns self

to_relative(prev)[source]
transform(transform)[source]
update_bounding_box(first, last_two_points, bbox)[source]
class inkex.paths.curve(dx2, dy2, dx3, dy3, dx4, dy4)[source]

Bases: inkex.paths.RelativePathCommand

Relative curved line segment

args
nargs = 6
to_absolute(prev)[source]
class inkex.paths.Smooth(x3, y3, x4, y4)[source]

Bases: inkex.paths.AbsolutePathCommand

Absolute Smoothed Curved Line segment

args
control_points(first, prev, prev_prev)[source]
end_point(first, prev)[source]
nargs = 4
to_curve(prev, prev_prev=Vector2d(0, 0))[source]

Convert this Smooth curve to a regular curve by creating a mirror set of nodes based on the previous node. Previous should be a curve.

to_relative(prev)[source]
transform(transform)[source]
update_bounding_box(first, last_two_points, bbox)[source]
class inkex.paths.smooth(dx3, dy3, dx4, dy4)[source]

Bases: inkex.paths.RelativePathCommand

Relative smoothed curved line segment

args
nargs = 4
to_absolute(prev)[source]
class inkex.paths.Quadratic(x2, y2, x3, y3)[source]

Bases: inkex.paths.AbsolutePathCommand

Absolute Quadratic Curved Line segment

args
control_points(first, prev, prev_prev)[source]
end_point(first, prev)[source]
nargs = 4
to_curve(prev, prev_prev=Vector2d(0, 0))[source]

Attempt to convert a quadratic to a curve

to_relative(prev)[source]
transform(transform)[source]
update_bounding_box(first, last_two_points, bbox)[source]
class inkex.paths.quadratic(dx2, dy2, dx3, dy3)[source]

Bases: inkex.paths.RelativePathCommand

Relative quadratic line segment

args
nargs = 4
to_absolute(prev)[source]
class inkex.paths.TepidQuadratic(x3, y3)[source]

Bases: inkex.paths.AbsolutePathCommand

Continued Quadratic Line segment

args
control_points(first, prev, prev_prev)[source]
end_point(first, prev)[source]
nargs = 2
to_curve(prev, prev_prev=Vector2d(0, 0))[source]
to_quadratic(prev, prev_prev)[source]

Convert this continued quadratic into a full quadratic

to_relative(prev)[source]
transform(transform)[source]
update_bounding_box(first, last_two_points, bbox)[source]
class inkex.paths.tepidQuadratic(dx3, dy3)[source]

Bases: inkex.paths.RelativePathCommand

Relative continued quadratic line segment

args
nargs = 2
to_absolute(prev)[source]
class inkex.paths.Arc(rx, ry, x_axis_rotation, large_arc, sweep, x, y)[source]

Bases: inkex.paths.AbsolutePathCommand

Special Arc segment

args
control_points(first, prev, prev_prev)[source]
end_point(first, prev)[source]
nargs = 7
to_curves(prev, prev_prev=Vector2d(0, 0))[source]

Convert this arc into bezier curves

to_relative(prev)[source]
transform(transform)[source]
update_bounding_box(first, last_two_points, bbox)[source]
class inkex.paths.arc(rx, ry, x_axis_rotation, large_arc, sweep, dx, dy)[source]

Bases: inkex.paths.RelativePathCommand

Relative Arc line segment

args
nargs = 7
to_absolute(prev)[source]
exception inkex.paths.InvalidPath[source]

Bases: ValueError

Raised when given an invalid path string

inkex.ports module

Common access to serial and other computer ports.

class inkex.ports.Serial(port, baud=9600, timeout=0.1, **options)[source]

Bases: object

Attempt to get access to the computer’s serial port.

with Serial(port_name, …) as com:
com.write(…)

Provides access to the debug/testing ports which are pretend ports able to accept the same input but allow for debugging.

static has_serial()[source]

Late importing of pySerial module

static list_ports()[source]

Return a list of available serial ports

set_options(stop=1, size=8, flow=None, parity=None)[source]

Set further options on the serial port

inkex.styles module

Two simple functions for working with inline css and some color handling on top.

class inkex.styles.AttrFallbackStyle(elem, move=False)[source]

Bases: object

A container for a style and an element that may have competing styles

If move is set to true, any new values are set to the style attribute and removed from the element attributes list.

get(name, default=None)[source]

Get with default

set(name, value)[source]

Set, nothing fancy

class inkex.styles.Classes(classes=None, callback=None)[source]

Bases: list

A list of classes applied to an element (used in css and js)

append(value)[source]
remove(value)[source]
toggle(value)[source]

If exists, remove it, if not, add it

class inkex.styles.ConditionalRule(rule)[source]

Bases: object

A single css rule

step_to_xpath = [(re.compile('\\[(\\w+)\\^=([^\\]]+)\\]'), '[starts-with(@\\1,\\2)]'), (re.compile('\\[(\\w+)\\$=([^\\]]+)\\]'), '[ends-with(@\\1,\\2)]'), (re.compile('\\[(\\w+)\\*=([^\\]]+)\\]'), '[contains(@\\1,\\2)]'), (re.compile('\\[([^@\\(\\)\\]]+)\\]'), '[@\\1]'), (re.compile('#(\\w+)'), "[@id='\\1']"), (re.compile('\\s*>\\s*([^\\s>~\\+]+)'), '/\\1'), (re.compile('\\s*([^\\s>~\\+]+)'), '//\\1'), (re.compile('\\.(\\w+)'), "[contains(concat(' ', normalize-space(@class), ' '), ' \\1 ')]"), (re.compile('//\\['), '//*['), (re.compile('//(\\w+)'), '//svg:\\1')]
to_xpath()[source]

Attempt to convert the rule into a simplified xpath

class inkex.styles.ConditionalStyle(rules='*', style=None, callback=None, **kwargs)[source]

Bases: inkex.styles.Style

Just like a Style object, but includes one or more conditional rules which places this style in a stylesheet rather than being an attribute style.

to_xpath()[source]

Convert all rules to an xpath

class inkex.styles.Style(style=None, callback=None, **kw)[source]

Bases: collections.OrderedDict

A list of style directives

color_props = ('stroke', 'fill', 'stop-color', 'flood-color', 'lighting-color')
get_color(name='fill')[source]

Get the color AND opacity as one Color object

opacity_props = ('stroke-opacity', 'fill-opacity', 'opacity')
static parse_str(style)[source]

Create a dictionary from the value of an inline style attribute

set_color(color, name='fill')[source]

Sets the given color AND opacity as rgba to the fill or stroke style properties.

to_str(sep=';')[source]

Convert to string using a custom delimiter

update(other)[source]

Make sure callback is called when updating

update_urls(old_id, new_id)[source]

Find urls in this style and replace them with the new id

class inkex.styles.StyleSheet(content=None, callback=None)[source]

Bases: list

A style sheet, usually the CDATA contents of a style tag, but also a css file used with a css. Will yield multiple Style() classes.

add(rule, style)[source]

Append a rule and style combo to this stylesheet

append(other)[source]

Make sure callback is called when updating

comment_strip = re.compile('//.*?\\n')
lookup(element_id, svg)[source]

Lookup the element_id against all the styles in this sheet

class inkex.styles.StyleSheets(svg=None)[source]

Bases: list

Special mechanism which contains all the stylesheets for an svg document while also caching lookups for specific elements.

This caching is needed because data can’t be attached to elements as they are re-created on the fly by lxml so lookups have to be centralised.

lookup(element_id, svg=None)[source]

Find all styles for this element.

inkex.transforms module

Provide transformation parsing to extensions

class inkex.transforms.BoundingBox(x, y=None)[source]

Bases: object

Some functions to compute a rough bbox of a given list of objects.

BoundingBox(other) BoundingBox(x, y) BoundingBox((x1, x2), (y1, y2))

static anchor_distance(x, y, direction=0, selbox=None)[source]

Using the x,y returns a single sortable value based on direction and angle

direction - int (custom angle), tb/bt (top/bottom), lr/rl (left/right), ri/ro (radial) selbox - The bounding box of the whole selection for radial anchors

bottom
center

Returns the middle of the bounding box

center_x
center_y
get_anchor(xanchor, yanchor, direction=None, selbox=None)[source]

Calls get_distance with the given anchor options

height
left
maximum

Return the maximum x,y coords

minimum

Return the minimum x,y coords

right
top
width
class inkex.transforms.DirectedLineSegment(*args)[source]

Bases: object

A directed line segment

DirectedLineSegment(((x0, y0), (x1, y1)))

angle

Get the angle of the line created by this segment

distance_to_point(x, y)[source]

Get the distance to the given point (x, y)

dot(other)[source]

Get the dot product with the segment with another

dx
dy
end = Vector2d(0, 0)
intersect(other)[source]

Get the intersection between two segments

length

Get the length from the top left to the bottom right of the line

parallel(x, y)[source]

Create parallel Segment

perp_distance(x, y)[source]

Perpendicular distance to the given point

point_at_length(length)[source]

Get the point as the length along the line

point_at_ratio(ratio)[source]

Get the point at the given ratio along the line

start = Vector2d(0, 0)
x0
x1
y0
y1
class inkex.transforms.ImmutableVector2d(*args)[source]

Bases: object

dot(other)[source]
is_close(other, rtol=1e-05, atol=1e-08)[source]
length
to_tuple()[source]
x
y
class inkex.transforms.Transform(matrix=None, callback=None, **extra)[source]

Bases: object

A transformation object which will always reduce to a matrix and can then be used in combination with other transformations for reducing finding a point and printing svg ready output.

Use with svg transform attribute input:

tr = Transform(“scale(45, 32)”)

Use with triad matrix input (internal representation):

tr = Transform(((1.0, 0.0, 0.0), (0.0, 1.0, 0.0)))

Use with hexad matrix input (i.e. svg matrix(…)):

tr = Transform((1.0, 0.0, 0.0, 1.0, 0.0, 0.0))

Once you have a transformation you can operate tr * tr to compose, any of the above inputs are also valid operators for composing.

TRM = re.compile('(translate|scale|rotate|skewX|skewY|matrix)\\s*\\(([^)]*)\\)\\s*,?')
a
absolute_tolerance = 1e-05
add_kwargs(**kwargs)[source]

Add translations, scales, rotations etc using key word arguments

add_matrix(*args)[source]

Add matrix in order they appear in the svg hexad

add_rotate(deg, *args)[source]

Add rotation to this transformation

add_scale(sc_x, sc_y=None)[source]

Add scale to this transformation

add_skewx(deg)[source]

Add skew x to this transformation

add_skewy(deg)[source]

Add skew y to this transformation

add_translate(*args)[source]
apply_to_point(point)[source]

Transform a tuple (X, Y)

b
c
d
e
f
is_rotate(exactly=False)[source]

Returns True if this transformation is ONLY rotate

is_scale(exactly=False)[source]

Returns True if this transformation is ONLY scale

is_translate(exactly=False)[source]

Returns True if this transformation is ONLY translate

rotation_degrees()[source]

Return the amount of rotation in this transform

to_hexad()[source]

Returns the transform as a hexad matrix (used in svg)

class inkex.transforms.Vector2d(*args)[source]

Bases: inkex.transforms.ImmutableVector2d

Represents an element of 2-dimensional Euclidean space

assign(*args)[source]
x
y

inkex.turtle module

class inkex.turtle.pTurtle(home=(0, 0))[source]

Bases: object

A Python path turtle

backward(mag)[source]
bk(mag)
clean()[source]
clear()[source]
fd(mag)
forward(mag)[source]
getPath()[source]
getheading()[source]
getpos()[source]
home()[source]
left(deg)[source]
lt(deg)
pd()
pendown()[source]
pentoggle()[source]
penup()[source]
pu()
right(deg)[source]
rt(deg)
rtree(size, minimum, pt=False)[source]
setheading(deg)[source]
sethome(arg)[source]
setpos(arg)[source]

inkex.tween module

inkex.tween.interpcoord(coord_a, coord_b, time)[source]

Interpolate single coordinate by the amount of time

inkex.tween.interppoints(point1, point2, time)[source]

Interpolate coordinate points by amount of time

inkex.tween.parsecolor(c)[source]
inkex.tween.tweenhex(time, s, e)[source]
inkex.tween.tweenstylecolor(prop, start, end, time)[source]
inkex.tween.tweenstylefloat(prop, start, end, time)[source]
inkex.tween.tweenstyleunit(svg, prop, start, end, time)[source]

inkex.units module

Convert to and from various units and find the closest matching unit.

inkex.units.are_near_relative(point_a, point_b, eps=0.01)[source]

Return true if the points are near to eps

inkex.units.convert_unit(value, to_unit)[source]

Returns userunits given a string representation of units in another system

inkex.units.discover_unit(value, viewbox, default='px')[source]

Attempt to detect the unit being used based on the viewbox

inkex.units.parse_unit(value, default_unit='px', default_value=None)[source]

Takes a value such as 55.32px and returns (55.32, ‘px’) Will returns default (None) if no match can be found

inkex.units.render_unit(value, unit)[source]

Checks and then renders a number with its unit

inkex.utils module

Basic common utility functions for calculated things

exception inkex.utils.AbortExtension(message='')[source]

Bases: Exception

Raised to print a message to the user without backtrace

write()[source]

write the error message out to the user

exception inkex.utils.DependencyError[source]

Bases: NotImplementedError

Raised when we need an external python module that isn’t available

inkex.utils.Boolean(value)[source]

ArgParser function to turn a boolean string into a python boolean

inkex.utils.errormsg(msg)[source]

Intended for end-user-visible error messages.

(Currently just writes to stderr with an appended newline, but could do something better in future: e.g. could add markup to distinguish error messages from status messages or debugging output.)

Note that this should always be combined with translation:

import inkex … inkex.errormsg(_(“This extension requires two selected paths.”))
inkex.utils.addNS(tag, ns=None)[source]

Add a known namespace to a name for use with lxml

Module contents

This describes the core API for the inkex core modules.

They provide the basis from which you can develop your inkscape extension.