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
Loader
struct. - Get an
SvgHandle
from theLoader
. - Create a
CairoRenderer
for theSvgHandle
and render to a Cairo context.
You can put the following in your Cargo.toml
:
[dependencies]
librsvg = "2.59.1"
cairo-rs = "0.20"
gio = "0.20" # 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_stream
without 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-
file
schemes are not allowed. For example, librsvg will not loadhttp
resources, to keep malicious SVG data from “phoning home”. -
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§
- Parser for an Accept-Language HTTP header.
- angle 🔒CSS angle values.
- api 🔒Public Rust API for librsvg.
- Handling of
preserveAspectRatio
values. - bbox 🔒Bounding boxes that know their coordinate space.
- color 🔒CSS color values.
- cond 🔒Conditional processing attributes:
requiredExtensions
,requiredFeatures
,systemLanguage
. userSpaceOnUse
orobjectBoundingBox
values.- css 🔒Representation of CSS types, and the CSS parsing and matching engine.
- Parser for the
stroke-dasharray
property. - document 🔒Main SVG document structure.
- dpi 🔒Resolution for rendering (dots per inch = DPI).
- The main context structure which drives the drawing process.
- element 🔒SVG Elements.
- error 🔒Error types.
- filter 🔒The
filter
element. - SVG2 filter function shortcuts -
blur()
,brightness()
, etc. - filters 🔒Entry point for the CSS filters infrastructure.
- Utilities to compare floating-point numbers.
- CSS font properties.
- gradient 🔒Gradient paint servers; the
linearGradient
andradialGradient
elements. - href 🔒Handling of
xlink:href
andhref
attributes - image 🔒The
image
element. - 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
marker
element, and geometry computations for markers. - node 🔒Tree nodes, the representation of SVG elements.
- SVG paint servers.
- parsers 🔒The
Parse
trait for CSS properties, and utilities for parsers. - Representation of Bézier paths.
- Parser for SVG path data.
- pattern 🔒The
pattern
element. - CSS properties, specified values, computed values.
- Definitions for CSS property types.
- 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
,ellipse
elements. - space 🔒Processing of the
xml:space
attribute. - Structural elements in SVG: the
g
,switch
,svg
,use
,symbol
,clip_path
,mask
,link
elements. - style 🔒The
style
element. - Various utilities for working with Cairo image surfaces.
- text 🔒Text elements:
text
,tspan
,tref
. - Handling of transform values.
- Type for values in the [0.0, 1.0] range.
- Determine which URLs are allowed for loading.
- util 🔒Miscellaneous utilities.
- viewbox 🔒Parser for the
viewBox
attribute. - xml 🔒The main XML parser.
Structs§
- Stores a parsed version of an HTTP Accept-Language header.
- Can render an
SvgHandle
to a Cairo context. - Contains the computed values of the
<svg>
element’swidth
,height
, andviewBox
. - A CSS length value.
- Builder for loading an
SvgHandle
. - Handle used to hold SVG data in memory.
- Holds the size of the current viewport in the user’s coordinate system.
Enums§
- Errors returned when looking up a resource by URL reference.
- Errors for implementation-defined limits, to mitigate malicious SVG documents.
- Used to set the language for rendering.
- Units for length values.
- Errors that can happen while loading an SVG document.
- Errors that can happen while rendering or measuring an SVG document.