Inkex 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.

abssolute_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

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

name

Return a fixed name for this extension

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.

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}" height="{height}"\n xmlns="http://www.w3.org/2000/svg" xmlns:svg="http://www.w3.org/2000/svg"\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_str(color)[source]

Creates a rgb int array

red
saturation
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_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

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=['-T', '-E', '-b', 'html', '-d', '_build/doctrees', '-D', 'language=en', '.', '_build/html'], 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.elements module

Provide extra utility to each svg element type specific to its type.

This is useful for having a common interface for each element which can give path, transform, and property access easily.

class inkex.elements.Group[source]

Bases: inkex.elements.ShapeElement

Any group element (layer or regular group)

bounding_box(transform=None)[source]

BoundingBox calculation based on the ShapeElement rendered to a path.

classmethod create(label, layer=False)[source]

Create a group, set the inkscape label and groupmode if needed

get_path()[source]

Generate a path for this object which can inform the bounding box

groupmode

Return the type of group this is

is_layer()
tag_name = 'g'
class inkex.elements.PathElement[source]

Bases: inkex.elements.ShapeElement

Provide a useful extension for path elements

apply_transform()[source]

Apply the internal transformation to this node and delete

get_path()
original_path

Returns the original path if this is an LPE, or the path if not

set_path(path)[source]

Set the given data as a path as the ‘d’ attribute

tag_name = 'path'
class inkex.elements.ShapeElement[source]

Bases: inkex.elements.BaseElement

Elements which have a visible representation on the canvas

bounding_box(transform=None)[source]

BoundingBox calculation based on the ShapeElement rendered to a path.

composed_style()[source]

Calculate the final styles applied to this element

composed_transform()[source]

Calculate every transform down to the root document node

get_center_position()[source]

Returns object’s center in terms of document units

get_path()[source]

Generate a path for this object which can inform the bounding box

href

Returns the referred-to element if available

label

Returns the inkscape label

path

Gets the outline or path of the element, this may be a simple bounding box

set_path(path)[source]

Set the path for this object (if possible)

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]

Apply some effects on the document or local context

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]

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

load_raw()[source]

Create the temporary directory

output_ext = 'svg'

inkex.localization module

Allow extensions to translate messages.

inkex.localization.localize()[source]

Turn on localisation for any platform

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

append(cmd)[source]

Append a command to this path including any chained commands

bounding_box()[source]

Return the top,left and bottom,right coords

control_points
copy()[source]

Make a copy

end_points
classmethod parse_string(path_d)[source]

Parse a path string and generate segment objects

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

to_path()[source]

Convert the super path back to an svg path

to_segments()[source]

Generate a set of segments for this cubic super path

transform(transform)[source]

Apply a transformation matrix to this super path

inkex.styles module

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

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

Bases: collections.OrderedDict

A list of style directives

static parse_str(style)[source]

Create a dictionary from the value of an inline style attribute

update(other)[source]

Make sure callback is called when updating

inkex.svg module

Provide a way to load lxml attributes with an svg API on top.

class inkex.svg.SvgDocumentElement[source]

Bases: inkex.elements.BaseElement

Provide access to the document level svg functionality

add_unit(value)[source]

Add document unit when no unit is specified in the string

defs

Return the svg defs meta element container

getElement(xpath)[source]

Gets a single element from the given xpath or returns None

getElementById(eid, elm='*')[source]

Get an element in this svg document by it’s ID attribute

get_center_position()[source]

Returns view_center in terms of document units

get_current_layer()[source]

Returns the currently selected layer

get_first_selected()[source]

Returns the first item in the selected list

get_ids()[source]

Returns a set of unique document ids

get_page_bbox()[source]

Gets the page dimentions as a bbox

get_selected_bbox()[source]

Gets the bounding box of the selected items

get_unique_id(prefix, size=4)[source]

Generate a new id from an existing old_id

get_viewbox()[source]

Parse and return the document’s viewBox attribute

get_z_selected()[source]

Get the selected elements, but ordered by their apperence in the document

height

Returns a string corresponding to the height of the document, as defined in the SVG file. If it is not defined, returns the height as defined by the viewBox attribute. If viewBox is not defined, returns the string ‘0’.

name

Returns the Document Name

namedview

Return the sp namedview meta information element

scale

Return the ratio between the page width and the viewBox width

set_selected(*ids)[source]

Sets the currently selected elements to these ids.

Arguments are zero or more ids, element objects or a single xpath expression starting with “//”.

All element objects must have an id to be correctly set.

>>> svg.set_selected("rect123", "path456", "text789")
>>> svg.set_selected(elem1, elem2, elem3)
>>> svg.set_selected("//rect")
tag_name = 'svg'
unit

Returns the unit used for in the SVG document. In the case the SVG document lacks an attribute that explicitly defines what units are used for SVG coordinates, it tries to calculate the unit from the SVG width and viewBox attributes. Defaults to ‘px’ units.

unittouu(value)[source]

Convert a unit value into the document’s units

uutounit(value, to_unit)[source]

Convert from the document’s units to the given unit

width

Fault tolerance for lazily defined SVG

inkex.transforms module

Provide transformation parsing to extensions

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_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.BoundingBox(x=None, y=None)[source]

Bases: object

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

BoundingBox() - Empty bounding box, bool == False BoundingBox(x) BoundingBox(x, y) BoundingBox((x1, x2, y1, y2)) BoundingBox((x1, x2), (y1, y2)) BoundingBox(((x1, y1), (x2, y2)))

bottom
center()[source]

Returns the middle of the bounding box

center_x
center_y
height
left
maximum

Return the maximum x,y coords

minimum

Return the minimum x,y coords

right
top
width

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

inkex.utils.inkbool(value)[source]

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.