Crate librsvg[][src]

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

You can put the following in your Cargo.toml:

[dependencies]
librsvg = { git="https://gitlab.gnome.org/GNOME/librsvg" }
cairo-rs = "0.8.0"
glib = "0.9.0"                                # only if you need streams
gio = { version="0.8.1", features=["v2_50"] } # likewise

Example


const WIDTH: i32 = 640;
const HEIGHT: i32 = 480;

fn main() {
    // Loading from a file

    let handle = librsvg::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 = librsvg::CairoRenderer::new(&handle);
    renderer.render_document(
        &cr,
        &cairo::Rectangle {
            x: 0.0,
            y: 0.0,
            width: f64::from(WIDTH),
            height: 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 = librsvg::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 /foo/bar/foo.svg and that it has an image element like this:

<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:

  1. All data: URLs may be loaded. These are sometimes used to include raster image data, encoded as base-64, directly in an SVG file.

  2. All other URL schemes in references require a base URL. For example, this means that if you load an SVG with Loader::read_stream without providing a base_file, then any referenced files will not be allowed (e.g. raster images to be loaded from other files will not work).

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

  4. 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).

  5. Otherwise, non-file schemes are not allowed. For example, librsvg will not load http resources, to keep malicious SVG data from “phoning home”.

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

c_api

C API for librsvg, based on GObject.

filters

Entry point for the CSS filters infrastructure.

log

Utilities for logging messages from the library.

surface_utils

Various utilities for working with Cairo image surfaces.

Macros

assert_approx_eq_cairo
borrow_element_as
coord_units

Creates a newtype around CoordUnits, with a default value.

enum_default
is_element_of_type
make_property

Generates a type for a CSS property.

parse_identifiers

Parses a list of identifiers from a cssparser::Parser

rsvg_c_str

Helper function for converting string literals to C char pointers.

rsvg_log
rsvg_return_if_fail

Replacement for g_return_if_fail().

rsvg_return_val_if_fail

Replacement for g_return_val_if_fail().

Structs

AcceptLanguage

Stores a parsed version of an HTTP Accept-Language header.

CairoRenderer

Can render an SvgHandle to a Cairo context.

IntrinsicDimensions

Contains the values of the <svg> element’s width, height, and viewBox attributes.

Length

A CSS length value.

Loader

Builder for loading an SvgHandle.

SvgHandle

Handle used to hold SVG data in memory.

Enums

Color

A value.

ImplementationLimit

Errors for implementation-defined limits, to mitigate malicious SVG documents.

Language

Used to set the language for rendering.

LengthUnit

Units for length values.

LoadingError

Errors that can happen while loading an SVG document.

RenderingError

Errors that can happen while rendering or measuring an SVG document.

UserLanguage

Language but with the environment’s locale converted to something we can use.

Traits

Parse

Trait to parse values using cssparser::Parser.

Type Definitions

IRect
Rect