SVG(3)
β¨ NAME β¨
SVG β the Perl extension for generating Scalable Vector Graphics (SVG) documents. Bestie, this is the manual page for SVG(3), and it's literally the blueprint for making vector art with Perl. No cap.
πΈ SYNOPSIS πΈ
Okay so here's the vibe. You write Perl, you make SVG. Watch:
#!/usr/bin/perl
use strict;
use warnings;
use SVG;
# create an SVG object
my $svg= SVG->new( width => 200, height => 200);
# use explicit element constructor to generate a group element
my $y = $svg->group(
id => 'group_y',
style => {
stroke => 'red',
fill => 'green'
},
);
# add a circle to the group
$y->circle( cx => 100, cy => 100, r => 50, id => 'circle_in_group_y' );
# or, use the generic 'tag' method to generate a group element by name
my $z = $svg->tag('g',
id => 'group_z',
style => {
stroke => 'rgb(100,200,50)',
fill => 'rgb(10,100,150)'
}
);
# create and add a circle using the generic 'tag' method
$z->tag('circle', cx => 50, cy => 50, r => 100, id => 'circle_in_group_z');
# create an anchor on a rectangle within a group within the group z
my $k = $z->anchor(
id => 'anchor_k',
-href => 'http://test.hackmare.com/',
target => 'new_window_0'
)->rectangle(
x => 20, y => 50,
width => 20, height => 30,
rx => 10, ry => 5,
id => 'rect_k_in_anchor_k_in_group_z'
);
# now render the SVG object, implicitly use svg namespace
print $svg->xmlify;
# or render a child node of the SVG object without rendering the entire object
print $k->xmlify; #renders the anchor $k above containing a rectangle, but does not
#render any of the ancestor nodes of $k
# or, explicitly use svg namespace and generate a document with its own DTD
print $svg->xmlify(-namespace=>'svg');
# or, explicitly use svg namespace and generate an inline docunent
print $svg->xmlify(
-namespace => "svg",
-pubid => "-//W3C//DTD SVG 1.0//EN",
-inline => 1
);
See the other modules in this distribution: SVG::DOM, SVG::XML, SVG::Element, and SVG::Extension.
See SVG::Parser for reading SVG files as "SVG" objects.
π¦ Converting SVG to PNG and other raster image formats π¦
The convert command of <http://www.imagemagick.org/> (also via Image::Magick ) can convert SVG files to PNG and other formats.
Image::LibRSVG can convert SVG to other format.
π EXAMPLES π
examples/circle.pl generates the following image:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.0//EN" "http://www.w3.org/TR/2001/REC-SVG-20010904/DTD/svg10.dtd">
<svg height="200" width="200" xmlns="http://www.w3.org/2000/svg" xmlns:svg="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
<title >I am a title</title>
<g id="group_y" style="fill: green; stroke: red">
<circle cx="100" cy="100" id="circle_in_group_y" r="50" />
<!-- This is a comment -->
</g>
</svg>
That you can either embed directly into HTML or can include it using:
<object data="file.svg" type="image/svg+xml"></object>
(The image was converted to png using Image::LibRSVG. See the svg2png.pl script in the examples directory.)
See also the examples directory in this distribution which contains several fully documented examples.
π DESCRIPTION π
SVG is a 100% Perl module which generates a nested data structure containing the DOM representation of an SVG (Scalable Vector Graphics) image. Using SVG, you can generate SVG objects, embed other SVG instances into it, access the DOM object, create and access javascript, and generate SMIL animation content.
π General Steps to generating an SVG document π
Generating SVG is a simple three step process:
- Construct a new SVG object with
new. - Call element constructors such as
circleandpathto create SVG elements. - Render the SVG object into XML using the
xmlifymethod.
The xmlify method takes a number of optional arguments that control how SVG renders the object into XML, and in particular determine whether a standalone SVG document or an inline SVG document fragment is generated:
π -standalone π
A complete SVG document with its own associated DTD. A namespace for the SVG elements may be optionally specified.
π -inline π
An inline SVG document fragment with no DTD that is embedded within other XML content. As with standalone documents, an alternate namespace may be specified.
No XML content is generated until the third step is reached. Up until this point, all constructed element definitions reside in a DOM-like data structure from which they can be accessed and modified.
π EXPORTS π
None. However, SVG permits both options and additional element methods to be specified in the import list. These options and elements are then available for all SVG instances that are created with the new constructor. For example, to change the indent string to two spaces per level:
use SVG (-indent => " ");
With the exception of -auto, all options may also be specified to the new constructor. The currently supported options and their default value are:
# processing options
-auto => 0, # permit arbitrary autoloading of all unrecognised elements
-printerror => 1, # print error messages to STDERR
-raiseerror => 1, # die on errors (implies -printerror)
# rendering options
-indent => "\t", # what to indent with
-elsep => "\n", # element line (vertical) separator
# (note that not all agents ignor trailing blanks)
-nocredits => 0, # enable/disable credit note comment
-namespace => '', # The root element's (and it's children's) namespace prefix
# XML and Doctype declarations
-inline => 0, # inline or stand alone
-docroot => 'svg', # The document's root element
-version => '1.0',
-extension => '',
-encoding => 'UTF-8',
-xml_svg => 'http://www.w3.org/2000/svg', # the svg xmlns attribute
-xml_xlink => 'http://www.w3.org/1999/xlink', # the svg tag xmlns:xlink attribute
-standalone => 'yes',
-pubid => "-//W3C//DTD SVG 1.0//EN", # formerly -identifier
-sysid => 'http://www.w3.org/TR/2001/REC-SVG-20010904/DTD/svg10.dtd', # the system id
SVG also allows additional element generation methods to be specified in the import list. For example to generate 'star' and 'planet' element methods:
use SVG qw(star planet);
or:
use SVG ("star","planet");
This will add 'star' to the list of elements supported by SVG.pm (but not of course other SVG parsers...). Alternatively the '-auto' option will allow any unknown method call to generate an element of the same name:
use SVG (-auto => 1, "star", "planet");
Any elements specified explicitly (as 'star' and 'planet' are here) are predeclared; other elements are defined as and when they are seen by Perl. Note that enabling '-auto' effectively disables compile-time syntax checking for valid method names.
use SVG (
-auto => 0,
-indent => " ",
-raiseerror => 0,
-printerror => 1,
"star", "planet", "moon"
);
π Default SVG tag π
The Default SVG tag will generate the following XML:
$svg = SVG->new;
print $svg->xmlify;
Resulting XML snippet:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.0//EN" "http://www.w3.org/TR/2001/REC-SVG-20010904/DTD/svg10.dtd">
<svg height="100%" width="100%" xmlns="http://www.w3.org/2000/svg" xmlns:svg="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
<!--
Generated using the Perl SVG Module V2.50
by Ronan Oger
-->
π₯ METHODS π₯
SVG provides both explicit and generic element constructor methods. Explicit generators are generally (with a few exceptions) named for the element they generate. If a tag method is required for a tag containing hyphens, the method name replaces the hyphen with an underscore. ie: to generate tag <column-heading id="new"> you would use method $svg->column_heading(id=>'new').
All element constructors take a hash of element attributes and options; element attributes such as 'id' or 'border' are passed by name, while options for the method (such as the type of an element that supports multiple alternate forms) are passed preceded by a hyphen, e.g '-type'. Both types may be freely intermixed; see the "fe" method and code examples throughout the documentation for more examples.
π new (constructor) π
$svg = SVG->new(%attributes)
Creates a new SVG object. Attributes of the document SVG element be passed as an optional list of key value pairs. Additionally, SVG options (prefixed with a hyphen) may be set on a per object basis:
my $svg1 = SVG->new;
my $svg2 = SVG->new(id => 'document_element');
my $svg3 = SVG->new(
-printerror => 1,
-raiseerror => 0,
-indent => ' ',
-docroot => 'svg', #default document root element (SVG specification assumes svg). Defaults to 'svg' if undefined
-sysid => 'abc', #optional system identifyer
-pubid => "-//W3C//DTD SVG 1.0//EN", #public identifyer default value is "-//W3C//DTD SVG 1.0//EN" if undefined
-namespace => 'mysvg',
-inline => 1
id => 'document_element',
width => 300,
height => 200,
);
SVG instance represents the document and not the <svg> root element.
Default SVG options may also be set in the import list. See "EXPORTS" above for more on the available options.
Furthermore, the following options:
-version
-encoding
-standalone
-namespace Defines the document or element level namespace. The order of assignment priority is element,document .
-inline
-identifier
-nostub
-dtd (standalone)
may also be set in xmlify, overriding any corresponding values set in the SVG->new declaration
β¨ xmlify (alias: to_xml render serialise serialize) β¨
$string = $svg->xmlify(%attributes);
Returns xml representation of svg document.
XML Declaration
okay so before we start generating literally every shape ever, here's the β¨vibe checkβ¨ on the default attributes you get when you spin up an SVG object. Name on the left, default value on the right, no cap:
-versionβ'1.0'-encodingβ'UTF-8'-standaloneβ'yes'-namespaceβ'svg'β this is the namespace for elements-inlineβ'0'β if you set it to'1', then this is an inline document.-pubidβ'-//W3C//DTD SVG 1.0//EN';-dtd(standalone) β'http://www.w3.org/TR/2001/REC-SVG-20010904/DTD/svg10.dtd'
tag (alias: element) π·οΈ
$tag = $svg->tag($name, %attributes)
The generic element generator, bestie. It makes the element named $name with all the attributes you hand it in %attributes. Lowkey this method is the blueprint behind basically every other explicit element generator on this whole page. Iconic behavior.
my $tag = $svg->tag('g', transform=>'rotate(-45)');
anchor β
$tag = $svg->anchor(%attributes)
Generates an anchor element. Anchors get wrapped around objects to make them 'live' (aka clickable, fr fr). So obviously it needs a drawn object or a group element as its child, otherwise there's nothing to click and that's just sad.
optional anchor attributes
These are the attributes you'd expect for anchor tags (and any any tags which use -href links, iykyk):
-hrefrequired-typeoptional-roleoptional-titleoptional-showoptional-arcroleoptional-actuateoptionaltargetoptional
Want the full tea on these options? Go read the w3c XLink specification at <http://www.w3.org/TR/xlink/> π
Example:
# generate an anchor
$tag = $SVG->anchor(
-href=>'http://here.com/some/simpler/SVG.SVG'
-title => 'new window 2 example title',
-actuate => 'onLoad',
-show=> 'embed',
);
For more info about the options above, go check the Link section in the SVG recommendation: <http://www.w3.org/TR/SVG11/linking.html#Links>
# add a circle to the anchor. The circle can be clicked on.
$tag->circle(cx => 10, cy => 10, r => 1);
# more complex anchor with both URL and target
$tag = $SVG->anchor(
-href => 'http://somewhere.org/some/other/page.html',
target => 'new_window'
);
# generate an anchor
$tag = $svg->anchor(
-href=>'http://here.com/some/simpler/svg.svg'
);
# add a circle to the anchor. The circle can be clicked on.
$tag->circle(cx => 10, cy => 10, r => 1);
# more complex anchor with both URL and target
$tag = $svg->anchor(
-href => 'http://somewhere.org/some/other/page.html',
target => 'new_window'
);
circle β
$tag = $svg->circle(%attributes)
Draws a circle at (cx,cy) with radius r. Simple, clean, slay.
my $tag = $svg->circle(cx => 4, cy => 2, r => 1);
ellipse π₯
$tag = $svg->ellipse(%attributes)
Draws an ellipse at (cx,cy) with radii rx,ry. A circle that decided to stretch, periodt.
use SVG;
# create an SVG object
my $svg= SVG->new( width => 200, height => 200);
my $tag = $svg->ellipse(
cx => 10,
cy => 10,
rx => 5,
ry => 7,
id => 'ellipse',
style => {
'stroke' => 'red',
'fill' => 'green',
'stroke-width' => '4',
'stroke-opacity' => '0.5',
'fill-opacity' => '0.2',
}
);
See The example/ellipse.pl π§
rectangle (alias: rect) π¦
$tag = $svg->rectangle(%attributes)
Draws a rectangle at (x,y) with width 'width' and height 'height' and side radii 'rx' and 'ry'.
$tag = $svg->rectangle(
x => 10,
y => 20,
width => 4,
height => 5,
rx => 5.2,
ry => 2.4,
id => 'rect_1'
);
image πΌοΈ
$tag = $svg->image(%attributes)
Draws an image at (x,y) with width 'width' and height 'height', linked to image resource '-href'. Also peep "use" while you're here, bestie.
$tag = $svg->image(
x => 100,
y => 100,
width => 300,
height => 200,
'-href' => "image.png", #may also embed SVG, e.g. "image.svg"
id => 'image_1'
);
Output:
<image xlink:href="image.png" x="100" y="100" width="300" height="200"/>
use β»οΈ
$tag = $svg->use(%attributes)
Grabs the content from an entity inside an SVG document and applies it at (x,y) with width 'width' and height 'height', linked to image resource '-href'. Reuse era π
$tag = $svg->use(
x => 100,
y => 100,
width => 300,
height => 200,
'-href' => "pic.svg#image_1",
id => 'image_1'
);
Output:
<use xlink:href="pic.svg#image_1" x="100" y="100" width="300" height="200"/>
Per the SVG specification, the 'use' element in SVG can point to a single element within an external SVG file. (Yes, a single element. Not the whole file. Read the spec, girlies.)
polygon π·
$tag = $svg->polygon(%attributes)
Draws an n-sided polygon with vertices at points defined by a string of the form 'x1,y1,x2,y2,x3,y3,... xy,yn'. The "get_path" method is right there as a convenience so you can generate a suitable string from coordinate data instead of typing all those numbers like it's 2003.
# a five-sided polygon
my $xv = [0, 2, 4, 5, 1];
my $yv = [0, 0, 2, 7, 5];
my $points = $svg->get_path(
x => $xv,
y => $yv,
-type =>'polygon'
);
my $poly = $svg->polygon(
%$points,
id => 'pgon1',
style => \%polygon_style
);
SEE ALSO:
"polyline", "path", "get_path".
polyline π
$tag = $svg->polyline(%attributes)
Draws an n-point polyline with points defined by a string of the form 'x1,y1,x2,y2,x3,y3,... xy,yn'. The "get_path" method is provided as a convenience to generate a suitable string from coordinate data.
# a 10-pointsaw-tooth pattern
my $xv = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
my $yv = [0, 1, 0, 1, 0, 1, 0, 1, 0, 1];
my $points = $svg->get_path(
x => $xv,
y => $yv,
-type => 'polyline',
-closed => 'true' #specify that the polyline is closed.
);
my $tag = $svg->polyline (
%$points,
id =>'pline_1',
style => {
'fill-opacity' => 0,
'stroke' => 'rgb(250,123,23)'
}
);
line π
$tag = $svg->line(%attributes)
Draws a straight line between two points (x1,y1) and (x2,y2). Short, sweet, to the point (pun fully intended).
my $tag = $svg->line(
id => 'l1',
x1 => 0,
y1 => 10,
x2 => 10,
y2 => 0,
);
Wanna draw multiple connected lines? That's "polyline" territory, bestie.
text βοΈ
$text = $svg->text(%attributes)->cdata();
$text_path = $svg->text(-type=>'path');
$text_span = $text_path->text(-type=>'span')->cdata('A');
$text_span = $text_path->text(-type=>'span')->cdata('B');
$text_span = $text_path->text(-type=>'span')->cdata('C');
Defines the container for a text string to be drawn in the image.
Input:
-type = path type (path | polyline | polygon)
-type = text element type (path | span | normal [default])
my $text1 = $svg->text(
id => 'l1',
x => 10,
y => 10
)->cdata('hello, world');
my $text2 = $svg->text(
id => 'l1',
x => 10,
y => 10,
-cdata => 'hello, world',
);
my $text = $svg->text(
id => 'tp',
x => 10,
y => 10,
-type => path,
)
->text(id=>'ts' -type=>'span')
->cdata('hello, world');
SEE ALSO:
"desc", "cdata".
title π
$tag = $svg->title(%attributes)
Generates the title of the image. Every masterpiece needs a name, no cap.
my $tag = $svg->title(id=>'document-title')->cdata('This is the title');
desc π
$svg->desc(id => 'image-description')->cdata('This image shows a red circle');
Adds a description element to the SVG document. The <desc> element provides a text-accessible description of the container or graphics element. It's primarily used for accessibility (screen readers, bestie β think of them π) and it is not rendered visually. Invisible but important, it's giving humble icon.
comment π¬
$svg->comment('Single comment');
$svg->comment('Part 1', 'Part 2', 'Part 3');
Adds a comment to the SVG document. Comments get rendered as standard XML comments. If you pass multiple strings, they get concatenated with spaces. And unlike the 'desc' element, comments are generally ignored by user agents and are not part of the DOM tree for accessibility. So don't put anything load-bearing in there, girlies.
pi (Processing Instruction) π§
$tag = $svg->pi(@pi)
Generates a set of processing instructions. Very niche, very demure.
my $tag = $svg->pi('instruction one','instruction two','instruction three');
returns:
<lt>?instruction one?<gt>
<lt>?instruction two?<gt>
<lt>?instruction three?<gt>
script β‘
$tag = $svg->script(%attributes)
Generates a script container for dynamic (client-side) scripting using ECMAscript, Javascript or other compatible scripting language. Time to make things move.
my $tag = $svg->script(-type=>"text/ecmascript");
#or my $tag = $svg->script();
#note that type ecmascript is not Mozilla compliant
# populate the script tag with cdata
# be careful to manage the javascript line ends.
# Use qq{text} or q{text} as appropriate.
# make sure to use the CAPITAL CDATA to poulate the script.
$tag->CDATA(qq{
function d() {
//simple display function
for(cnt = 0; cnt < d.length; cnt++)
document.write(d[cnt]);//end for loop
document.write("<BR>");//write a line break
}
});
Fr fr: use the CAPITALCDATAto populate the script. The lowercasecdatais a whole different thing and it will not do what you want here. π
path π€οΈ
$tag = $svg->path(%attributes)
Draws a path element. The path vertices can be handed over as a parameter or calculated with the "get_path" method. Your call, main character.
# a 10-pointsaw-tooth pattern drawn with a path definition
my $xv = [0,1,2,3,4,5,6,7,8,9];
my $yv = [0,1,0,1,0,1,0,1,0,1];
$points = $svg->get_path(
x => $xv,
y => $yv,
-type => 'path',
-closed => 'true' #specify that the polyline is closed
);
$tag = $svg->path(
%$points,
id => 'pline_1',
style => {
'fill-opacity' => 0,
'fill' => 'green',
'stroke' => 'rgb(250,123,23)'
}
);
SEE ALSO: "get_path".
get_path π§
$path = $svg->get_path(%attributes)
Returns the text string of points, correctly formatted so you can drop it right into the multi-point SVG drawing object definitions (path, polyline, polygon). It's the little helper that does the math so you don't have to β¨
Input: attributes including:
okay bestie, so back to get_path β here's the 411 on what you feed it and what it hands back. π
-typeβ path type (path|polyline|polygon)xβ reference to array of x coordinatesyβ reference to array of y coordinates
Output: a hash reference consisting of the following key-value pair:
pointsβ the appropriate points-definition string-typeβpath|polygon|polyline-relativeβ1(define relative position rather than absolute position)-closedβ1(close the curve - path and polygon only)
#generate an open path definition for a path.
my ($points,$p);
$points = $svg->get_path(x=>\@x,y=>\@y,-relative=>1,-type=>'path');
#add the path to the SVG document
my $p = $svg->path(%$path, style=>\%style_definition);
#generate an closed path definition for a a polyline.
$points = $svg->get_path(
x=>\@x,
y=>\@y,
-relative=>1,
-type=>'polyline',
-closed=>1
); # generate a closed path definition for a polyline
# add the polyline to the SVG document
$p = $svg->polyline(%$points, id=>'pline1');
Note: The attribute returned depends on the element type: "-type => 'path'" returns "{ d => ... }", while "-type => 'polygon'" and "-type => 'polyline'" return "{ points => ... }".
Aliases: get_path set_path
animate π¬β¨
$tag = $svg->animate(%attributes)
Spins up a SMIL animation tag. This is allowed within any nonempty tag. Refer to the W3C for detailed information on the subtleties of the animate SMIL commands. W3C has the deep lore, so go check that if you want the nitty-gritty. π¦
Inputs: -method = Transform | Motion | Color
my $an_ellipse = $svg->ellipse(
cx => 30,
cy => 150,
rx => 10,
ry => 10,
id => 'an_ellipse',
stroke => 'rgb(130,220,70)',
fill =>'rgb(30,20,50)'
);
$an_ellipse-> animate(
attributeName => "cx",
values => "20; 200; 20",
dur => "10s",
repeatDur => 'indefinite'
);
$an_ellipse-> animate(
attributeName => "rx",
values => "10;30;20;100;50",
dur => "10s",
repeatDur => 'indefinite',
);
$an_ellipse-> animate(
attributeName => "ry",
values => "30;50;10;20;70;150",
dur => "15s",
repeatDur => 'indefinite',
);
$an_ellipse-> animate(
attributeName=>"rx",values=>"30;75;10;100;20;20;150",
dur=>"20s", repeatDur=>'indefinite');
$an_ellipse-> animate(
attributeName=>"fill",values=>"red;green;blue;cyan;yellow",
dur=>"5s", repeatDur=>'indefinite');
$an_ellipse-> animate(
attributeName=>"fill-opacity",values=>"0;1;0.5;0.75;1",
dur=>"20s",repeatDur=>'indefinite');
$an_ellipse-> animate(
attributeName=>"stroke-width",values=>"1;3;2;10;5",
dur=>"20s",repeatDur=>'indefinite');
group π―βοΈπ
$tag = $svg->group(%attributes)
Define a group of objects with common properties. Groups can have style, animation, filters, transformations, and mouse actions assigned to them. It's giving squad goals for your SVG elements. β¨
$tag = $svg->group(
id => 'xvs000248',
style => {
'font' => [ qw( Arial Helvetica sans ) ],
'font-size' => 10,
'fill' => 'red',
},
transform => 'rotate(-45)'
);
defs π¦β¨
$tag = $svg->defs(%attributes)
define a definition segment. A Defs requires children when defined using SVG.pm. Don't leave it childless, bestie, it needs its little ones. π₯Ί
$tag = $svg->defs(id => 'def_con_one',);
style π π¨
$svg->tag('style', %styledef);
Sets/adds style-definition for the following objects being created.
Style definitions apply to an object and all its children for all properties for which the value of the property is not redefined by the child. It's like passing down your iconic fashion sense to your kids. π
$tag = $SVG->style(%attributes)
Generate a style container for inline or xlink:href based styling instructions. The way that this slays is unreal.
my $tag = $SVG->style(type=>"text/css");
# Populate the style tag with cdata.
# Be careful to manage the line ends.
# Use qq{text}, where text is the script
$tag1->CDATA(qq{
rect fill:red;stroke:green;
circle fill:red;stroke:orange;
ellipse fill:none;stroke:yellow;
text fill:black;stroke:none;
});
# Create a external CSS stylesheet reference
my $tag2 = $SVG->style(type=>"text/css", -href="/resources/example.css");
mouseaction π±οΈβ¨
$svg->mouseaction(%attributes)
Sets/Adds mouse action definitions for tag. Make it interactive, periodt. π
attrib π·οΈπ
$svg->attrib($name, $value)
Sets/adds attributes of an element. It's literally the main character of attribute management.
Retrieve an attribute:
$svg->attrib($name);
Set a scalar attribute:
$SVG->attrib $name, $value
Set a list attribute:
$SVG->attrib $name, \@value
Set a hash attribute (i.e. style definitions):
$SVG->attrib $name, \%value
Remove an attribute:
$svg->attrib($name,undef);
Aliases: attr attribute
Sets/replaces attributes for a tag.
cdata πβ¨
$svg->cdata($text)
Sets cdata to $text. SVG.pm allows you to set cdata for any tag. If the tag is meant to be an empty tag, SVG.pm will not complain, but the rendering agent will fail. In the SVG DTD, cdata is generally only meant for adding text or script content. So don't be messy, okay? π
$svg->text(
style => {
'font' => 'Arial',
'font-size' => 20
})->cdata('SVG.pm is a perl module on CPAN!');
my $text = $svg->text( style => { 'font' => 'Arial', 'font-size' => 20 } );
$text->cdata('SVG.pm is a perl module on CPAN!');
Result:
<text style="font: Arial; font-size: 20">SVG.pm is a perl module on CPAN!</text>
SEE ALSO:
"CDATA", "desc", "title", "text", "script".
cdata_noxmlesc π«π€β¨
$script = $svg->script(); $script->cdata_noxmlesc($text);
Generates cdata content for text and similar tags which do not get xml-escaped. In other words, does not parse the content and inserts the exact string into the cdata location. No filter, just vibes. β¨
CDATA ποΈβ¨
$script = $svg->script(); $script->CDATA($text);
Generates a <![CDATA[ ... ]]> tag with the contents of $text rendered exactly as supplied. SVG.pm allows you to set cdata for any tag. If the tag is meant to be an empty tag, SVG.pm will not complain, but the rendering agent will fail. In the SVG DTD, cdata is generally only meant for adding text or script content. It's iconic, but use it wisely. π
my $text = qq{
var SVGDoc;
var groups = new Array();
var last_group;
/*****
*
* init
*
* Find this SVG's document element
* Define members of each group by id
*
*****/
function init(e) {
SVGDoc = e.getTarget().getOwnerDocument();
append_group(1, 4, 6); // group 0
append_group(5, 4, 3); // group 1
append_group(2, 3); // group 2
}};
$svg->script()->CDATA($text);
Result:
<script >
<![CDATA[
var SVGDoc;
var groups = new Array();
var last_group;
/*****
*
* init
*
* Find this SVG's document element
* Define members of each group by id
*
*****/
function init(e) {
SVGDoc = e.getTarget().getOwnerDocument();
append_group(1, 4, 6); // group 0
append_group(5, 4, 3); // group 1
append_group(2, 3); // group 2
}
]]>
SEE ALSO: "cdata", "script".
xmlescp and xmlescape π§Όβ¨
$string = $svg->xmlescp($string) $string = $svg->xmlesc($string) $string = $svg->xmlescape($string)
SVG module does not xml-escape characters that are incompatible with the XML specification. xmlescp and xmlescape provides this functionality. It is a helper function which generates an XML-escaped string for reserved characters such as ampersand, open and close brackets, etcetera. Basically it's the hygiene check for your strings. π§Ό
The behaviour of xmlesc is to apply the following transformation to the input string $s:
$s=~s/&(?!#(x\w\w|\d+?);)/&/g;
$s=~s/>/>/g;
$s=~s/</</g;
$s=~s/\"/"/g;
$s=~s/\'/'/g;
$s=~s/([\x00-\x08\x0b\x1f])/''/eg;
$s=~s/([\200-\377])/'&#'.ord($1).';'/ge;
filter π§½β¨
$tag = $svg->filter(%attributes)
Generate a filter. Filter elements contain "fe" filter sub-elements. It's giving Photoshop energy for your SVGs. π
my $filter = $svg->filter(
filterUnits=>"objectBoundingBox",
x=>"-10%",
y=>"-10%",
width=>"150%",
height=>"150%",
filterUnits=>'objectBoundingBox'
);
$filter->fe();
SEE ALSO: "fe".
fe β¨ποΈ
$tag = $svg->fe(-type=>'type', %attributes)
Generate a filter sub-element. Must be a child of a "filter" element. No cap, it has to be nested.
my $fe = $svg->fe(
-type => 'DiffuseLighting' # required - element name omitting 'fe'
id => 'filter_1',
style => {
'font' => [ qw(Arial Helvetica sans) ],
'font-size' => 10,
'fill' => 'red',
},
transform => 'rotate(-45)'
);
Note that the following filter elements are currently supported: Also note that the elelemts are defined in lower case in the module, but as of version 2.441, any case combination is allowed. (Yes, we said elelemts, but you know what we mean. π)
- feBlend
- feColorMatrix
- feComponentTransfer
- feComposite
- feConvolveMatrix
- feDiffuseLighting
- feDisplacementMap
- feDistantLight
- feFlood
- feFuncA
- feFuncB
- feFuncG
- feFuncR
- feGaussianBlur
- feImage
- feMerge
- feMergeNode
- feMorphology
- feOffset
- fePointLight
- feSpecularLighting
- feSpotLight
- feTile
- feTurbulence
SEE ALSO: "filter".
pattern π§Άβ¨
$tag = $svg->pattern(%attributes)
Define a pattern for later reference by url. It's the ultimate reusable vibe. π¦
my $pattern = $svg->pattern(
id => "Argyle_1",
width => "50",
height => "50",
patternUnits => "userSpaceOnUse",
patternContentUnits => "userSpaceOnUse"
);
set πβ¨
$tag = $svg->set(%attributes)
Set a definition for an SVG object in one section, to be referenced in other sections as needed. It's like saving a draft for later, bestie. π
my $set = $svg->set(
id => "Argyle_1",
width => "50",
height => "50",
patternUnits => "userSpaceOnUse",
patternContentUnits => "userSpaceOnUse"
);
stop πβ¨
$tag = $svg->stop(%attributes)
Define a stop boundary for "gradient". It's the final stop on the gradient train, no cap. π
my $pattern = $svg->stop(
id => "Argyle_1",
width => "50",
height => "50",
patternUnits => "userSpaceOnUse",
patternContentUnits => "userSpaceOnUse"
);
gradient
$tag = $svg->gradient(%attributes)
Okay bestie, this one is giving COLOR β¨ it defines a color gradient, and it can be of type linear or radial. Two flavors, both iconic.
my $gradient = $svg->gradient(
-type => "linear",
id => "gradient_1"
);
π GENERIC ELEMENT METHODS π
So these next elements are generically supported by SVG β no bespoke method needed, they just vibe through the generic constructor. The full roster, no skips:
altGlyphaltGlyphDefaltGlyphItemclipPathcolor-profilecursordefinition-srcfont-face-formatfont-face-namefont-face-srcfont-face-urlforeignObjectglyphglyphRefhkernmarkermaskmetadatamissing-glyphmpathswitchsymboltrefviewvkern
Peep e.g. "pattern" for an example of the use of these methods π
π¦ METHODS IMPORTED BY SVG::DOM π¦
These SVG::DOM elements are all reachable through SVG, periodt:
getChildrengetFirstChildgetNextChildgetLastChildgetParentgetParentElementgetSiblingsgetElementByIDgetElementIDgetElementsgetElementNamegetTypegetAttributesgetAttributesetAttributessetAttributeinsertBeforeinsertAfterinsertSiblingBeforeinsertSiblingAfterreplaceChildremoveChildcloneNode
Methods
SVG hands you both explicit and generic element constructor methods. The explicit generators are generally (a few exceptions, don't come for me) named for the element they generate. Now here's the tea: if you need a tag method for a tag containing hyphens, the method name swaps the hyphen for an underscore. Like, to generate tag <column-heading id="new"> you'd use method $svg->column_heading(id=>'new'). Slay π
All element constructors take a hash of element attributes and options. Element attributes like 'id' or 'border' are passed by name, while options for the method (like the type of an element that supports multiple alternate forms) get passed with a hyphen in front, e.g. '-type'. Both types may be freely intermixed, bestie, mix away. See the "fe" method and code examples all over the docs for more.
new (constructor)
$svg = SVG->new(%attributes)
Creates a new SVG object, main character energy only. Attributes of the document SVG element get passed as an optional list of key value pairs. And lowkey you can also set SVG options (hyphen-prefixed, obviously) on a per-object basis:
my $svg1 = SVG->new;
my $svg2 = SVG->new(id => 'document_element');
my $svg3 = SVG->new(
-printerror => 1,
-raiseerror => 0,
-indent => ' ',
-elsep => "\n", # element line (vertical) separator
-docroot => 'svg', # default document root element (SVG specification assumes svg). Defaults to 'svg' if undefined
-xml_xlink => 'http://www.w3.org/1999/xlink', # required by Mozilla's embedded SVG engine
-sysid => 'abc', # optional system identifier
-pubid => "-//W3C//DTD SVG 1.0//EN", # public identifier default value is "-//W3C//DTD SVG 1.0//EN" if undefined
-namespace => 'mysvg',
-inline => 1
id => 'document_element',
width => 300,
height => 200,
);
Default SVG options can also be set in the import list β scroll up to "EXPORTS" for more on the available options π«Ά
And furthermore (yes, we're still going), these options:
-version
-encoding
-standalone
-namespace
-inline
-pubid (formerly -identifier)
-sysid (standalone)
may also be set in xmlify, overriding any corresponding values set in the SVG->new declaration. Override szn π₯
xmlify (alias: to_xml render serialize serialise)
$string = $svg->xmlify(%attributes);
Returns the xml representation of the svg document. Here's your XML Declaration defaults, cutie:
-versionβ default value'1.0'-encodingβ default value'UTF-8'-standaloneβ default value'yes'-namespaceβ default value'svg'β namespace prefix for elements. Can also be used in any element method to over-ride the current namespace prefix. Make sure to have declared the prefix before using it, fr fr.-inlineβ default value'0'β if'1', then this is an inline document.-pubidβ default value'-//W3C//DTD SVG 1.0//EN'-sysidβ default value'http://www.w3.org/TR/2001/REC-SVG-20010904/DTD/svg10.dtd'
perlify ()
Returns the perl code which generates the SVG document as it currently exists. It's giving reverse engineering but make it cute β¨
toperl ()
Alias for method perlify(). Same thing, different name, we love options.
π AUTHOR π
Ronan Oger, RO IT Systemms GmbH, cpan@roitsystems.com
π MAINTAINER π
Mohammad Sajid Anwar <https://manwar.org/>
πΈ CREDITS πΈ
Gotta thank the people who contributed patches, testing, suggestions, and other nice tidbits β absolute legends, every one:
Peter Wainwright, Excellent ideas, beta-testing, writing SVG::Parser and much of SVG::DOM. Fredo, http://www.penguin.at0.net/~fredo/ - provided example code and initial feedback for early SVG.pm versions and the idea of a simplified svg generator. Adam Schneider Brial PilprΓ© Ian Hickson Steve Lihn Allen Day Martin Owens - SVG::DOM improvements in version 3.34
π COPYRIGHT & LICENSE π
Copyright 2001- Ronan Oger
The modules in the SVG distribution are distributed under the same license as Perl itself. It is provided free of warranty and may be re-used freely. No cap β free is free π«Ά
β ARTICLES β
- SVG using Perl <http://szabgab.com/svg-using-perl.html>
- SVG - Scalable Vector Graphics with Perl <http://perlmaven.com/scalable-vector-graphics-with-perl>
- Combining SVG and PSGI <http://perlmaven.com/combining-svg-and-psgi>
π SEE ALSO π
SVG::DOM, SVG::XML, SVG::Element, SVG::Parser, SVG::Extension
For Commercial Perl/SVG development, refer to the following sites: SVG at the W3C <http://www.w3c.org/Graphics/SVG/>.
And that's a wrap on the whole page, bestie π
You just read SVG(3) β this came from perl v5.42.0, dated 2026-03-13. Go make something pretty with it π¦β¨
π¦ where this page comes from
- fedora 44: perl-SVG 2.89-1.fc44 Β· GPL-1.0-or-later OR Artistic-1.0-Perl
- π girlified by deepseek-ai/DeepSeek-V4.1-Flash on : a language model's rewrite of the original, under its terms