Expand description
Load and render SVG images into Cairo surfaces.
This crate can load SVG images and render them to Cairo surfaces, using a mixture of SVG’s static mode and secure static mode. Librsvg does not do animation nor scripting, and can load references to external data only in some situations; see below.
Librsvg supports reading SVG 1.1 data, and is gradually adding support for features in SVG 2. Librsvg also supports SVGZ files, which are just an SVG stream compressed with the GZIP algorithm.
§Basic usage
- Create a
Loaderstruct. - Get an
SvgHandlefrom theLoader. - Create a
CairoRendererfor theSvgHandleand render to a Cairo context.
You can put the following in your Cargo.toml:
[dependencies]
librsvg = "2.62.0-beta.0"
cairo-rs = "0.22.0-alpha"
gio = "0.22.0-alpha" # only if you need streams§Example
const WIDTH: i32 = 640;
const HEIGHT: i32 = 480;
fn main() {
// Loading from a file
let handle = rsvg::Loader::new().read_path("example.svg").unwrap();
let surface = cairo::ImageSurface::create(cairo::Format::ARgb32, WIDTH, HEIGHT).unwrap();
let cr = cairo::Context::new(&surface).expect("Failed to create a cairo context");
let renderer = rsvg::CairoRenderer::new(&handle);
renderer.render_document(
&cr,
&cairo::Rectangle::new(0.0, 0.0, f64::from(WIDTH), f64::from(HEIGHT))
).unwrap();
// Loading from a static SVG asset
let bytes = glib::Bytes::from_static(
br#"<?xml version="1.0" encoding="UTF-8"?>
<svg xmlns="http://www.w3.org/2000/svg" width="50" height="50">
<rect id="foo" x="10" y="10" width="30" height="30"/>
</svg>
"#
);
let stream = gio::MemoryInputStream::from_bytes(&bytes);
let handle = rsvg::Loader::new().read_stream(
&stream,
None::<&gio::File>, // no base file as this document has no references
None::<&gio::Cancellable>, // no cancellable
).unwrap();
}§The “base file” and resolving references to external files
When you load an SVG, librsvg needs to know the location of the “base file”
for it. This is so that librsvg can determine the location of referenced
entities. For example, say you have an SVG in
<image href="resources/foo.png" .../>In this case, librsvg needs to know the location of the toplevel
/foo/bar/foo.svg so that it can generate the appropriate
reference to /foo/bar/resources/foo.png.
§Security and locations of referenced files
When processing an SVG, librsvg will only load referenced files if
they are in the same directory as the base file, or in a
subdirectory of it. That is, if the base file is
/foo/bar/baz.svg, then librsvg will only try to load referenced
files (from SVG’s <image> element, for example, or from content
included through XML entities) if those files are in /foo/bar/*
or in /foo/bar/*/.../*. This is so that malicious SVG documents
cannot include files that are in a directory above.
The full set of rules for deciding which URLs may be loaded is as follows; they are applied in order. A referenced URL will not be loaded as soon as one of these rules fails:
-
All
data:URLs may be loaded. These are sometimes used to include raster image data, encoded as base-64, directly in an SVG file. -
URLs with queries (“?”) or fragment identifiers (“#”) are not allowed.
-
All URL schemes other than data: in references require a base URL. For example, this means that if you load an SVG with
Loader::read_streamwithout providing abase_file, then any referenced files will not be allowed (e.g. raster images to be loaded from other files will not work). -
If referenced URLs are absolute, rather than relative, then they must have the same scheme as the base URL. For example, if the base URL has a “
file” scheme, then all URL references inside the SVG must also have the “file” scheme, or be relative references which will be resolved against the base URL. -
If referenced URLs have a “
resource” scheme, that is, if they are included into your binary program with GLib’s resource mechanism, they are allowed to be loaded (provided that the base URL is also a “resource”, per the previous rule). -
Otherwise, non-
fileschemes are not allowed. For example, librsvg will not loadhttpresources, to keep malicious SVG data from “phoning home”. -
URLs with a
filescheme are rejected if they contain a hostname, as infile://hostname/some/directory/foo.svg. Windows UNC paths with a hostname are also rejected. This is to prevent documents from trying to access resources on other machines. -
A relative URL must resolve to the same directory as the base URL, or to one of its subdirectories. Librsvg will canonicalize filenames, by removing “
..” path components and resolving symbolic links, to decide whether files meet these conditions.
Modules§
- accept_
language 🔒 - Parser for an Accept-Language HTTP header.
- angle 🔒
- CSS angle values.
- api 🔒
- Public Rust API for librsvg.
- aspect_
ratio 🔒 - Handling of
preserveAspectRatiovalues. - bbox 🔒
- Bounding boxes that know their coordinate space.
- cairo_
path 🔒 - Utilities for dealing with Cairo paths.
- color 🔒
- CSS color values.
- cond 🔒
- Conditional processing attributes:
requiredExtensions,requiredFeatures,systemLanguage. - coord_
units 🔒 userSpaceOnUseorobjectBoundingBoxvalues.- css 🔒
- Representation of CSS types, and the CSS parsing and matching engine.
- dasharray 🔒
- Parser for the
stroke-dasharrayproperty. - document 🔒
- Main SVG document structure.
- dpi 🔒
- Resolution for rendering (dots per inch = DPI).
- drawing_
ctx 🔒 - The main context structure which drives the drawing process.
- element 🔒
- SVG Elements.
- error 🔒
- Error types.
- filter 🔒
- The
filterelement. - filter_
func 🔒 - SVG2 filter function shortcuts -
blur(),brightness(), etc. - filters 🔒
- Entry point for the CSS filters infrastructure.
- float_
eq_ 🔒cairo - Utilities to compare floating-point numbers.
- font_
props 🔒 - CSS font properties.
- gradient 🔒
- Gradient paint servers; the
linearGradientandradialGradientelements. - href 🔒
- Handling of
xlink:hrefandhrefattributes - image 🔒
- The
imageelement. - io 🔒
- Utilities to acquire streams and data from from URLs.
- iri 🔒
- CSS funciri values.
- layout 🔒
- Layout tree.
- length 🔒
- CSS length values.
- limits 🔒
- Processing limits to mitigate malicious SVGs.
- log 🔒
- Utilities for logging messages from the library.
- marker 🔒
- The
markerelement, and geometry computations for markers. - node 🔒
- Tree nodes, the representation of SVG elements.
- paint_
server 🔒 - SVG paint servers.
- parsers 🔒
- The
Parsetrait for CSS properties, and utilities for parsers. - path_
builder 🔒 - Representation of Bézier paths.
- path_
parser 🔒 - Parser for SVG path data.
- pattern 🔒
- The
patternelement. - properties 🔒
- CSS properties, specified values, computed values.
- property_
defs 🔒 - Definitions for CSS property types.
- property_
macros 🔒 - Macros to define CSS properties.
- rect 🔒
- Types for rectangles.
- session 🔒
- Tracks metadata for a loading/rendering session.
- shapes 🔒
- Basic SVG shapes: the
path,polygon,polyline,line,rect,circle,ellipseelements. - space 🔒
- Processing of the
xml:spaceattribute. - structure 🔒
- Structural elements in SVG: the
g,switch,svg,use,symbol,clip_path,mask,linkelements. - style 🔒
- The
styleelement. - surface_
utils 🔒 - Various utilities for working with Cairo image surfaces.
- text 🔒
- Text elements:
text,tspan,tref. - text2 🔒
- transform 🔒
- Handling of transform values.
- unit_
interval 🔒 - Type for values in the [0.0, 1.0] range.
- url_
resolver 🔒 - Determine which URLs are allowed for loading.
- util 🔒
- Miscellaneous utilities.
- viewbox 🔒
- Parser for the
viewBoxattribute. - xml 🔒
- The main XML parser.
Structs§
- Accept
Language - Stores a parsed version of an HTTP Accept-Language header.
- Cairo
Renderer - Can render an
SvgHandleto a Cairo context. - Intrinsic
Dimensions - Contains the computed values of the
<svg>element’swidth,height, andviewBox. - Length
- A CSS length value.
- Loader
- Builder for loading an
SvgHandle. - SvgHandle
- Handle used to hold SVG data in memory.
- Viewport
- Holds the size of the current viewport in the user’s coordinate system.
Enums§
- Defs
Lookup Error Kind - Errors returned when looking up a resource by URL reference.
- Implementation
Limit - Errors for implementation-defined limits, to mitigate malicious SVG documents.
- Language
- Used to set the language for rendering.
- Length
Unit - Units for length values.
- Loading
Error - Errors that can happen while loading an SVG document.
- Rendering
Error - Errors that can happen while rendering or measuring an SVG document.