Class Handle
- All Implemented Interfaces:
Proxy
Handle loads an SVG document into memory.
This is the main entry point into the librsvg library. An Handle is an
object that represents SVG data in memory. Your program creates an
Handle from an SVG file, or from a memory buffer that contains SVG data,
or in the most general form, from a GInputStream that will provide SVG data.
Librsvg 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.
[static mode]: https://www.w3.org/TR/SVG2/conform.htmlstatic-mode
[secure static mode]: https://www.w3.org/TR/SVG2/conform.htmlsecure-static-mode
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/<anything> or in /foo/bar/<anything>\\/.../<anything>.
This is so that malicious SVG files 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. URLs with queries ("?") or fragment identifiers ("") are not allowed.
3. All URL schemes other than data: in references require a base URL. For
example, this means that if you load an SVG with
fromData(byte[]) without calling setBaseUri(java.lang.String),
then any referenced files will not be allowed (e.g. raster images to be
loaded from other files will not work).
4. 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.
5. 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).
6. Otherwise, non-file schemes are not allowed. For
example, librsvg will not load http resources, to keep
malicious SVG data from "phoning home".
7. URLs with a file scheme are rejected if they contain a hostname, as in
file://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.
8. 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.
Loading an SVG with GIO
This is the easiest and most resource-efficient way of loading SVG data into
an Handle.
If you have a GFile that stands for an SVG file, you can simply call
fromGfileSync(org.gnome.gio.File, java.util.Set<org.gnome.rsvg.HandleFlags>, org.gnome.gio.Cancellable) to load an Handle from it.
Alternatively, if you have a GInputStream, you can use
fromStreamSync(org.gnome.gio.InputStream, org.gnome.gio.File, java.util.Set<org.gnome.rsvg.HandleFlags>, org.gnome.gio.Cancellable).
Both of those methods allow specifying a GCancellable, so the loading
process can be cancelled from another thread.
Loading an SVG from memory
If you already have SVG data in a byte buffer in memory, you can create a
memory input stream with MemoryInputStream.fromData(byte[]) and feed that
to fromStreamSync(org.gnome.gio.InputStream, org.gnome.gio.File, java.util.Set<org.gnome.rsvg.HandleFlags>, org.gnome.gio.Cancellable).
Note that in this case, it is important that you specify the base_file for the in-memory SVG data. Librsvg uses the base_file to resolve links to external content, like raster images.
Loading an SVG without GIO
You can load an Handle from a simple filename or URI with
fromFile(java.lang.String). Note that this is a blocking operation; there
is no way to cancel it if loading a remote URI takes a long time. Also, note that
this method does not let you specify Rsvg.HandleFlags.
Otherwise, loading an SVG without GIO is not recommended, since librsvg will
need to buffer your entire data internally before actually being able to
parse it. The deprecated way of doing this is by creating a handle with
Handle() or withFlags(java.util.Set<org.gnome.rsvg.HandleFlags>), and then using
write(byte[]) and close() to feed the handle with SVG data.
Still, please try to use the GIO stream functions instead.
Resolution of the rendered image (dots per inch, or DPI)
SVG images can contain dimensions like "5cm" or
"2pt" that must be converted from physical units into
device units. To do this, librsvg needs to know the actual dots per inch
(DPI) of your target device. You can call setDpi(double) or
setDpiXY(double, double) on an Handle to set the DPI before rendering
it.
For historical reasons, the default DPI is 90. Current CSS assumes a default DPI of 96, so
you may want to set the DPI of a Handle immediately after creating it with
setDpi(double).
Rendering
The preferred way to render a whole SVG document is to use
renderDocument(org.freedesktop.cairo.Context, org.gnome.rsvg.Rectangle). Please see its documentation for
details.
API ordering
Due to the way the librsvg API evolved over time, an Handle object is available
for use as soon as it is constructed. However, not all of its methods can be
called at any time. For example, an Handle just constructed with Handle()
is not loaded yet, and it does not make sense to call renderDocument(org.freedesktop.cairo.Context, org.gnome.rsvg.Rectangle) on it
just at that point.
The documentation for the available methods in Handle may mention that a particular
method is only callable on a "fully loaded handle". This means either:
- The handle was loaded with
write(byte[])andclose(), and those functions returned no errors.
- The handle was loaded with
readStreamSync(org.gnome.gio.InputStream, org.gnome.gio.Cancellable)and that function returned no errors.
Before librsvg 2.46, the library did not fully verify that a handle was in a
fully loaded state for the methods that require it. To preserve
compatibility with old code which inadvertently called the API without
checking for errors, or which called some methods outside of the expected
order, librsvg will just emit a g_critical() message in those cases.
New methods introduced in librsvg 2.46 and later will check for the correct ordering, and panic if they are called out of order. This will abort the program as if it had a failed assertion.
-
Nested Class Summary
Nested ClassesModifier and TypeClassDescriptionstatic classHandle.Builder<B extends Handle.Builder<B>>Inner class implementing a builder pattern to construct a GObject with properties.static classClass structure forHandle.Nested classes/interfaces inherited from class org.gnome.gobject.GObject
GObject.NotifyCallback, GObject.ObjectClass -
Constructor Summary
ConstructorsConstructorDescriptionHandle()Creates a new Handle.Handle(MemorySegment address) Create a Handle proxy instance for the provided memory address. -
Method Summary
Modifier and TypeMethodDescriptionprotected HandleasParent()Returns this instance as if it were its parent type.static Handle.Builder<? extends Handle.Builder> builder()AHandle.Builderobject constructs aHandlewith the specified properties.booleanclose()Deprecated.voidfree()Deprecated.UseGObject.unref()instead.static HandlefromData(@org.jspecify.annotations.Nullable byte @Nullable [] data) Loads the SVG specified bydata.Note that this function creates anHandlewithout a base URL, and without anyRsvg.HandleFlags.static HandleLoads the SVG specified byfileName.Note that this function, likeHandle(), does not specify any loading flags for the resulting handle.static HandlefromGfileSync(File file, Set<HandleFlags> flags, @Nullable Cancellable cancellable) Creates a newHandleforfile.static @Nullable HandlefromGfileSync(File file, HandleFlags flags, @Nullable Cancellable cancellable) Creates a newHandleforfile.static HandlefromStreamSync(InputStream inputStream, @Nullable File baseFile, Set<HandleFlags> flags, @Nullable Cancellable cancellable) Creates a newHandleforstream.static @Nullable HandlefromStreamSync(InputStream inputStream, @Nullable File baseFile, HandleFlags flags, @Nullable Cancellable cancellable) Creates a newHandleforstream.Gets the base uri for thisHandle.@Nullable StringgetDesc()Deprecated.voidgetDimensions(DimensionData dimensionData) booleangetDimensionsSub(DimensionData dimensionData, @Nullable String id) booleangetGeometryForElement(@Nullable String id, @Nullable Rectangle outInkRect, @Nullable Rectangle outLogicalRect) Computes the ink rectangle and logical rectangle of a single SVG element.booleangetGeometryForLayer(@Nullable String id, Rectangle viewport, @Nullable Rectangle outInkRect, @Nullable Rectangle outLogicalRect) Computes the ink rectangle and logical rectangle of an SVG element, or the whole SVG, as if the whole SVG were rendered to a specific viewport.voidgetIntrinsicDimensions(@Nullable Out<Boolean> outHasWidth, @Nullable Length outWidth, @Nullable Out<Boolean> outHasHeight, @Nullable Length outHeight, @Nullable Out<Boolean> outHasViewbox, @Nullable Rectangle outViewbox) In simple terms, queries thewidth,height, andviewBoxattributes in an SVG document.booleangetIntrinsicSizeInPixels(@Nullable Out<Double> outWidth, @Nullable Out<Double> outHeight) Converts an SVG document's intrinsic dimensions to pixels, and returns the result.static MemoryLayoutThe memory layout of the native struct.@Nullable StringDeprecated.@Nullable PixbufDeprecated.UsegetPixbufAndError().@Nullable PixbufReturns the pixbuf loaded byhandle.The pixbuf returned will be reffed, so the caller of this function must assume that ref.@Nullable PixbufgetPixbufSub(@Nullable String id) Creates aGdkPixbufthe same size as the entire SVG loaded intohandle,but only renders the sub-element that has the specifiedid(and all its sub-sub-elements recursively).booleangetPositionSub(PositionData positionData, @Nullable String id) @Nullable StringgetTitle()Deprecated.static @Nullable TypegetType()Get the GType of the Handle classbooleanChecks whether the elementidexists in the SVG document.voidinternalSetTesting(boolean testing) Do not call this function.booleanreadStreamSync(InputStream stream, @Nullable Cancellable cancellable) Readsstreamand writes the data from it tohandle.booleanrenderCairo(org.freedesktop.cairo.Context cr) Deprecated.Please userenderDocument(org.freedesktop.cairo.Context, org.gnome.rsvg.Rectangle)instead; that function lets you pass a viewport and obtain a good error message.booleanrenderCairoSub(org.freedesktop.cairo.Context cr, @Nullable String id) Deprecated.Please userenderLayer(org.freedesktop.cairo.Context, java.lang.String, org.gnome.rsvg.Rectangle)instead; that function lets you pass a viewport and obtain a good error message.booleanrenderDocument(org.freedesktop.cairo.Context cr, Rectangle viewport) Renders the whole SVG document fitted to a viewport.booleanrenderElement(org.freedesktop.cairo.Context cr, @Nullable String id, Rectangle elementViewport) Renders a single SVG element to a given viewport.booleanrenderLayer(org.freedesktop.cairo.Context cr, @Nullable String id, Rectangle viewport) Renders a single SVG element in the same place as for a whole SVG document.voidsetBaseGfile(File baseFile) Set the base URI for this Handle fromfile.voidsetBaseUri(String baseUri) Set the base URI for this SVG.voidsetCancellableForRendering(@Nullable Cancellable cancellable) Sets a cancellable object that can be used to interrupt rendering while the handle is being rendered in another thread.voidsetDpi(double dpi) Sets the DPI at which the this Handle will be rendered.voidsetDpiXY(double dpiX, double dpiY) Sets the DPI at which the this Handle will be rendered.voidsetSizeCallback(@Nullable SizeFunc sizeFunc) Deprecated.booleansetStylesheet(@org.jspecify.annotations.Nullable byte @Nullable [] css) Sets a CSS stylesheet to use for an SVG document.static HandlewithFlags(Set<HandleFlags> flags) Creates a newHandlewith flagsflags.After calling this function, you can feed the resulting handle with SVG data by usingreadStreamSync(org.gnome.gio.InputStream, org.gnome.gio.Cancellable).static HandlewithFlags(HandleFlags... flags) Creates a newHandlewith flagsflags.After calling this function, you can feed the resulting handle with SVG data by usingreadStreamSync(org.gnome.gio.InputStream, org.gnome.gio.Cancellable).booleanwrite(@org.jspecify.annotations.Nullable byte @Nullable [] buf) Deprecated.UsereadStreamSync(org.gnome.gio.InputStream, org.gnome.gio.Cancellable)or the constructor functionsfromGfileSync(org.gnome.gio.File, java.util.Set<org.gnome.rsvg.HandleFlags>, org.gnome.gio.Cancellable)orfromStreamSync(org.gnome.gio.InputStream, org.gnome.gio.File, java.util.Set<org.gnome.rsvg.HandleFlags>, org.gnome.gio.Cancellable).Methods inherited from class org.gnome.gobject.GObject
addToggleRef, addWeakPointer, bindProperty, bindProperty, bindProperty, bindPropertyFull, bindPropertyFull, bindPropertyWithClosures, bindPropertyWithClosures, compatControl, connect, connect, connect, constructed, disconnect, dispatchPropertiesChanged, dispose, dupData, dupQdata, emit, emitNotify, finalize_, forceFloating, freezeNotify, get, getData, getProperty, getProperty, getProperty, getQdata, getv, interfaceFindProperty, interfaceInstallProperty, interfaceListProperties, isFloating, newInstance, newInstance, newv, notify, notify, notifyByPspec, onNotify, ref, refSink, removeToggleRef, removeWeakPointer, replaceData, replaceQdata, runDispose, set, setData, setDataFull, setProperty, setProperty, setProperty, setQdata, setQdataFull, setv, stealData, stealQdata, takeRef, thawNotify, unref, watchClosure, weakRef, weakUnref, withPropertiesMethods inherited from class org.gnome.gobject.TypeInstance
callParent, callParent, cast, getPrivate, readGClass, writeGClassMethods inherited from class org.javagi.base.ProxyInstance
equals, handle, hashCode
-
Constructor Details
-
Handle
Create a Handle proxy instance for the provided memory address.- Parameters:
address- the memory address of the native object
-
Handle
public Handle()Creates a new Handle.
-
-
Method Details
-
getType
-
getMemoryLayout
The memory layout of the native struct.- Returns:
- the memory layout
-
asParent
Returns this instance as if it were its parent type. This is mostly synonymous to the Javasuperkeyword, but will set the native typeclass function pointers to the parent type. When overriding a native virtual method in Java, "chaining up" withsuper.methodName()doesn't work, because it invokes the overridden function pointer again. To chain up, callasParent().methodName(). This will call the native function pointer of this virtual method in the typeclass of the parent type. -
fromData
public static Handle fromData(@org.jspecify.annotations.Nullable byte @Nullable [] data) throws GErrorException Loads the SVG specified bydata.Note that this function creates anHandlewithout a base URL, and without anyRsvg.HandleFlags. If you need these, usefromStreamSync(org.gnome.gio.InputStream, org.gnome.gio.File, java.util.Set<org.gnome.rsvg.HandleFlags>, org.gnome.gio.Cancellable)instead by creating aMemoryInputStreamfrom your data.- Parameters:
data- The SVG data- Returns:
- A
HandleorNULLif an error occurs. - Throws:
GErrorException- seeGError- Since:
- 2.14
-
fromFile
Loads the SVG specified byfileName.Note that this function, likeHandle(), does not specify any loading flags for the resulting handle. If you require the use ofRsvg.HandleFlags, usefromGfileSync(org.gnome.gio.File, java.util.Set<org.gnome.rsvg.HandleFlags>, org.gnome.gio.Cancellable).- Parameters:
filename- The file name to load, or a URI.- Returns:
- A
HandleorNULLif an error occurs. - Throws:
GErrorException- seeGError- Since:
- 2.14
-
fromGfileSync
public static Handle fromGfileSync(File file, Set<HandleFlags> flags, @Nullable Cancellable cancellable) throws GErrorException Creates a newHandleforfile.This function sets the "base file" of the handle to be
fileitself, so SVG elements like<image>which reference external resources will be resolved relative to the location offile.If
cancellableis notNULL, then the operation can be cancelled by triggering the cancellable object from another thread. If the operation was cancelled, the errorG_IO_ERROR_CANCELLEDwill be returned inerror.- Parameters:
file- aGFileflags- flags fromRsvg.HandleFlagscancellable- aGCancellable, orNULL- Returns:
- a new
Handleon success, orNULLwitherrorfilled in - Throws:
GErrorException- seeGError- Since:
- 2.32
-
fromGfileSync
public static @Nullable Handle fromGfileSync(File file, HandleFlags flags, @Nullable Cancellable cancellable) throws GErrorException Creates a newHandleforfile.This function sets the "base file" of the handle to be
fileitself, so SVG elements like<image>which reference external resources will be resolved relative to the location offile.If
cancellableis notNULL, then the operation can be cancelled by triggering the cancellable object from another thread. If the operation was cancelled, the errorG_IO_ERROR_CANCELLEDwill be returned inerror.- Parameters:
file- aGFileflags- flags fromRsvg.HandleFlagscancellable- aGCancellable, orNULL- Returns:
- a new
Handleon success, orNULLwitherrorfilled in - Throws:
GErrorException- seeGError- Since:
- 2.32
-
fromStreamSync
public static Handle fromStreamSync(InputStream inputStream, @Nullable File baseFile, Set<HandleFlags> flags, @Nullable Cancellable cancellable) throws GErrorException Creates a newHandleforstream.This function sets the "base file" of the handle to be
baseFileif provided. SVG elements like<image>which reference external resources will be resolved relative to the location ofbaseFile.If
cancellableis notNULL, then the operation can be cancelled by triggering the cancellable object from another thread. If the operation was cancelled, the errorG_IO_ERROR_CANCELLEDwill be returned inerror.- Parameters:
inputStream- aGInputStreambaseFile- aGFile, orNULLflags- flags fromRsvg.HandleFlagscancellable- aGCancellable, orNULL- Returns:
- a new
Handleon success, orNULLwitherrorfilled in - Throws:
GErrorException- seeGError- Since:
- 2.32
-
fromStreamSync
public static @Nullable Handle fromStreamSync(InputStream inputStream, @Nullable File baseFile, HandleFlags flags, @Nullable Cancellable cancellable) throws GErrorException Creates a newHandleforstream.This function sets the "base file" of the handle to be
baseFileif provided. SVG elements like<image>which reference external resources will be resolved relative to the location ofbaseFile.If
cancellableis notNULL, then the operation can be cancelled by triggering the cancellable object from another thread. If the operation was cancelled, the errorG_IO_ERROR_CANCELLEDwill be returned inerror.- Parameters:
inputStream- aGInputStreambaseFile- aGFile, orNULLflags- flags fromRsvg.HandleFlagscancellable- aGCancellable, orNULL- Returns:
- a new
Handleon success, orNULLwitherrorfilled in - Throws:
GErrorException- seeGError- Since:
- 2.32
-
withFlags
Creates a newHandlewith flagsflags.After calling this function, you can feed the resulting handle with SVG data by usingreadStreamSync(org.gnome.gio.InputStream, org.gnome.gio.Cancellable).- Parameters:
flags- flags fromRsvg.HandleFlags- Returns:
- a new
Handle - Since:
- 2.36
-
withFlags
Creates a newHandlewith flagsflags.After calling this function, you can feed the resulting handle with SVG data by usingreadStreamSync(org.gnome.gio.InputStream, org.gnome.gio.Cancellable).- Parameters:
flags- flags fromRsvg.HandleFlags- Returns:
- a new
Handle - Since:
- 2.36
-
close
Deprecated.UsereadStreamSync(org.gnome.gio.InputStream, org.gnome.gio.Cancellable)or the constructor functionsfromGfileSync(org.gnome.gio.File, java.util.Set<org.gnome.rsvg.HandleFlags>, org.gnome.gio.Cancellable)orfromStreamSync(org.gnome.gio.InputStream, org.gnome.gio.File, java.util.Set<org.gnome.rsvg.HandleFlags>, org.gnome.gio.Cancellable). See the deprecation notes forwrite(byte[])for more information.This is used after callingwrite(byte[])to indicate that there is no more data to consume, and to start the actual parsing of the SVG document. The only reason to call this function is if you use usewrite(byte[])to feed data into thehandle;if you use the other methods likefromFile(java.lang.String)orreadStreamSync(org.gnome.gio.InputStream, org.gnome.gio.Cancellable), then you do not need to call this function.This will return
TRUEif the loader closed successfully and the SVG data was parsed correctly. Note that this Handle isn't freed untilGObject.unref()is called.- Returns:
TRUEon success, orFALSEon error.- Throws:
GErrorException- seeGError
-
free
-
getBaseUri
-
getDesc
Deprecated. -
getDimensions
Deprecated.UsegetIntrinsicSizeInPixels(org.javagi.base.Out<java.lang.Double>, org.javagi.base.Out<java.lang.Double>)instead. This function is deprecated because it is not able to return exact fractional dimensions, only integer pixels.Get the SVG's size. Do not call from within the size_func callback, because an infinite loop will occur.This function depends on the
Handle's DPI to compute dimensions in pixels, so you should callsetDpi(double)beforehand.- Parameters:
dimensionData- A place to store the SVG's size- Since:
- 2.14
-
getDimensionsSub
Deprecated.Get the size of a subelement of the SVG file. Do not call from within the size_func callback, because an infinite loop will occur.This function depends on the
Handle's DPI to compute dimensions in pixels, so you should callsetDpi(double)beforehand.Element IDs should look like an URL fragment identifier; for example, pass
#foo(hashfoo) to get the geometry of the element that has anid="foo"attribute.- Parameters:
dimensionData- A place to store the SVG's sizeid- An element's id within the SVG, starting with ""(a single hash character), for example,#layer1. This notation corresponds to a URL's fragment ID. Alternatively, passNULLto use the whole SVG.- Returns:
TRUEif the dimensions could be obtained,FALSEif there was an error.- Since:
- 2.22
-
getGeometryForElement
public boolean getGeometryForElement(@Nullable String id, @Nullable Rectangle outInkRect, @Nullable Rectangle outLogicalRect) throws GErrorException Computes the ink rectangle and logical rectangle of a single SVG element.While
rsvg_handle_get_geometry_for_layercomputes the geometry of an SVG element subtree with its transformation matrix, this other function will compute the element's geometry as if it were being rendered under an identity transformation by itself. That is, the resulting geometry is as if the element got extracted by itself from the SVG.This function is the counterpart to
rsvg_handle_render_element.Element IDs should look like an URL fragment identifier; for example, pass
#foo(hashfoo) to get the geometry of the element that has anid="foo"attribute.The "ink rectangle" is the bounding box that would be painted for fully- stroked and filled elements.
The "logical rectangle" just takes into account the unstroked paths and text outlines.
Note that these bounds are not minimum bounds; for example, clipping paths are not taken into account.
You can pass
NULLfor theidif you want to measure all the elements in the SVG, i.e. to measure everything from the root element.This operation is not constant-time, as it involves going through all the child elements.
- Parameters:
id- An element's id within the SVG, starting with ""(a single hash character), for example,#layer1. This notation corresponds to a URL's fragment ID. Alternatively, passNULLto compute the geometry for the whole SVG.outInkRect- Place to store the ink rectangle of the element.outLogicalRect- Place to store the logical rectangle of the element.- Returns:
TRUEif the geometry could be obtained, orFALSEon error. Errors are returned in theerrorargument.API ordering: This function must be called on a fully-loaded
handle.See the section "API ordering" for details.Panics: this function will panic if the this Handle is not fully-loaded.
- Throws:
GErrorException- seeGError- Since:
- 2.46
-
getGeometryForLayer
public boolean getGeometryForLayer(@Nullable String id, Rectangle viewport, @Nullable Rectangle outInkRect, @Nullable Rectangle outLogicalRect) throws GErrorException Computes the ink rectangle and logical rectangle of an SVG element, or the whole SVG, as if the whole SVG were rendered to a specific viewport.Element IDs should look like an URL fragment identifier; for example, pass
#foo(hashfoo) to get the geometry of the element that has anid="foo"attribute.The "ink rectangle" is the bounding box that would be painted for fully-stroked and filled elements.
The "logical rectangle" just takes into account the unstroked paths and text outlines.
Note that these bounds are not minimum bounds; for example, clipping paths are not taken into account.
You can pass
NULLfor theidif you want to measure all the elements in the SVG, i.e. to measure everything from the root element.This operation is not constant-time, as it involves going through all the child elements.
- Parameters:
id- An element's id within the SVG, starting with ""(a single hash character), for example,#layer1. This notation corresponds to a URL's fragment ID. Alternatively, passNULLto compute the geometry for the whole SVG.viewport- Viewport size at which the whole SVG would be fitted.outInkRect- Place to store the ink rectangle of the element.outLogicalRect- Place to store the logical rectangle of the element.- Returns:
TRUEif the geometry could be obtained, orFALSEon error. Errors are returned in theerrorargument.API ordering: This function must be called on a fully-loaded
handle.See the section "API ordering" for details.Panics: this function will panic if the this Handle is not fully-loaded.
- Throws:
GErrorException- seeGError- Since:
- 2.46
-
getIntrinsicDimensions
public void getIntrinsicDimensions(@Nullable Out<Boolean> outHasWidth, @Nullable Length outWidth, @Nullable Out<Boolean> outHasHeight, @Nullable Length outHeight, @Nullable Out<Boolean> outHasViewbox, @Nullable Rectangle outViewbox) In simple terms, queries thewidth,height, andviewBoxattributes in an SVG document.If you are calling this function to compute a scaling factor to render the SVG, consider simply using
renderDocument(org.freedesktop.cairo.Context, org.gnome.rsvg.Rectangle)instead; it will do the scaling computations automatically.Before librsvg 2.54.0, the
out_has_widthandout_has_heightarguments would be set to true or false depending on whether the SVG document actually hadwidthandheightattributes, respectively.However, since librsvg 2.54.0,
widthandheightare now geometry properties per the SVG2 specification; they are not plain attributes. SVG2 made it so that the initial value of those properties isauto, which is equivalent to specifing a value of100%. In this sense, even SVG documents which lackwidthorheightattributes semantically have to make them default to100%. This is why since librsvg 2.54.0,out_has_widthandout_has_heigthare always returned asTRUE, since with SVG2 all documents have a default width and height of100%.As an example, the following SVG element has a
widthof 100 pixels and aheightof 400 pixels, but noviewBox. This function will return those sizes inout_widthandout_height, and setout_has_viewboxtoFALSE.<svg xmlns="http://www.w3.org/2000/svg" width="100" height="400">Conversely, the following element has a
viewBox, but nowidthorheight. This function will setout_has_viewboxtoTRUE, and it will also setout_has_widthandout_has_heighttoTRUEbut return both length values as100%.<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 400">Note that the
RsvgLengthreturn values haveRsvgUnitsin them; you should not assume that they are always in pixels. For example, the following SVG element will return width and height values whoseunitsfields areRSVG_UNIT_MM.<svg xmlns="http://www.w3.org/2000/svg" width="210mm" height="297mm">API ordering: This function must be called on a fully-loaded
handle.See the section "API ordering" for details.Panics: this function will panic if the this Handle is not fully-loaded.
- Parameters:
outHasWidth- Will be set toTRUE; see below.outWidth- Will be set to the computed value of thewidthproperty in the toplevel SVG.outHasHeight- Will be set toTRUE; see below.outHeight- Will be set to the computed value of theheightproperty in the toplevel SVG.outHasViewbox- Will be set toTRUEif the toplevel SVG has aviewBoxattributeoutViewbox- Will be set to the value of theviewBoxattribute in the toplevel SVG- Since:
- 2.46
-
getIntrinsicSizeInPixels
public boolean getIntrinsicSizeInPixels(@Nullable Out<Double> outWidth, @Nullable Out<Double> outHeight) Converts an SVG document's intrinsic dimensions to pixels, and returns the result.This function is able to extract the size in pixels from an SVG document if the document has both
widthandheightattributes with physical units (px, in, cm, mm, pt, pc) or font-based units (em, ex). For physical units, the dimensions are normalized to pixels using the dots-per-inch (DPI) value set previously withsetDpi(double). For font-based units, this function uses the computed value of thefont-sizeproperty for the toplevel<svg>element. In those cases, this function returnsTRUE.For historical reasons, the default DPI is 90. Current CSS assumes a default DPI of 96, so you may want to set the DPI of a
Handleimmediately after creating it withsetDpi(double).This function is not able to extract the size in pixels directly from the intrinsic dimensions of the SVG document if the
widthorheightare in percentage units (or if they do not exist, in which case the SVG spec mandates that they default to 100%), as these require a <firstterm>viewport</firstterm> to be resolved to a final size. In this case, the function returnsFALSE.For example, the following document fragment has intrinsic dimensions that will resolve to 20x30 pixels.
<svg xmlns="http://www.w3.org/2000/svg" width="20" height="30"/>Similarly, if the DPI is set to 96, this document will resolve to 192×288 pixels (i.e. 96×2 × 96×3).
<svg xmlns="http://www.w3.org/2000/svg" width="2in" height="3in"/>The dimensions of the following documents cannot be resolved to pixels directly, and this function would return
FALSEfor them:<!-- Needs a viewport against which to compute the percentages. --> <svg xmlns="http://www.w3.org/2000/svg" width="100%" height="100%"/> <!-- Does not have intrinsic width/height, just a 1:2 aspect ratio which needs to be fitted within a viewport. --> <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 200"/>Instead of querying an SVG document's size, applications are encouraged to render SVG documents to a size chosen by the application, by passing a suitably-sized viewport to
renderDocument(org.freedesktop.cairo.Context, org.gnome.rsvg.Rectangle).- Parameters:
outWidth- Will be set to the computed width; you should round this up to get integer pixels.outHeight- Will be set to the computed height; you should round this up to get integer pixels.- Returns:
TRUEif the dimensions could be converted directly to pixels; in this caseoutWidthandoutHeightwill be set accordingly. Note that the dimensions are floating-point numbers, so your application can know the exact size of an SVG document. To get integer dimensions, you should useceil()to round up to the nearest integer (just usinground(), may may chop off pixels with fractional coverage). If the dimensions cannot be converted to pixels, returnsFALSEand puts 0.0 in bothoutWidthandoutHeight.- Since:
- 2.52
-
getMetadata
Deprecated. -
getPixbuf
Deprecated.UsegetPixbufAndError().Returns the pixbuf loaded byhandle.The pixbuf returned will be reffed, so the caller of this function must assume that ref.API ordering: This function must be called on a fully-loaded
handle.See the section "API ordering" for details.This function depends on the
Handle's dots-per-inch value (DPI) to compute the "natural size" of the document in pixels, so you should callsetDpi(double)beforehand.- Returns:
- A pixbuf, or
nullon error during rendering.
-
getPixbufAndError
Returns the pixbuf loaded byhandle.The pixbuf returned will be reffed, so the caller of this function must assume that ref.API ordering: This function must be called on a fully-loaded
handle.See the section "API ordering" for details.This function depends on the
Handle's dots-per-inch value (DPI) to compute the "natural size" of the document in pixels, so you should callsetDpi(double)beforehand.- Returns:
- A pixbuf, or
nullon error during rendering. - Throws:
GErrorException- seeGError- Since:
- 2.59
-
getPixbufSub
Creates aGdkPixbufthe same size as the entire SVG loaded intohandle,but only renders the sub-element that has the specifiedid(and all its sub-sub-elements recursively). IfidisNULL, this function renders the whole SVG.This function depends on the
Handle's dots-per-inch value (DPI) to compute the "natural size" of the document in pixels, so you should callsetDpi(double)beforehand.If you need to render an image which is only big enough to fit a particular sub-element of the SVG, consider using
renderElement(org.freedesktop.cairo.Context, java.lang.String, org.gnome.rsvg.Rectangle).Element IDs should look like an URL fragment identifier; for example, pass
#foo(hashfoo) to get the geometry of the element that has anid="foo"attribute.API ordering: This function must be called on a fully-loaded
handle.See the section "API ordering" for details.- Parameters:
id- An element's id within the SVG, starting with ""(a single hash character), for example,#layer1. This notation corresponds to a URL's fragment ID. Alternatively, passNULLto use the whole SVG.- Returns:
- a pixbuf, or
NULLif an error occurs during rendering. - Since:
- 2.14
-
getPositionSub
Deprecated.UsegetGeometryForLayer(java.lang.String, org.gnome.rsvg.Rectangle, org.gnome.rsvg.Rectangle, org.gnome.rsvg.Rectangle)instead. This function is deprecated since it is not able to return exact floating-point positions, only integer pixels.Get the position of a subelement of the SVG file. Do not call from within the size_func callback, because an infinite loop will occur.This function depends on the
Handle's DPI to compute dimensions in pixels, so you should callsetDpi(double)beforehand.Element IDs should look like an URL fragment identifier; for example, pass
#foo(hashfoo) to get the geometry of the element that has anid="foo"attribute.- Parameters:
positionData- A place to store the SVG fragment's position.id- An element's id within the SVG, starting with ""(a single hash character), for example,#layer1. This notation corresponds to a URL's fragment ID. Alternatively, passnullto use the whole SVG.- Returns:
TRUEif the position could be obtained,FALSEif there was an error.- Since:
- 2.22
-
getTitle
Deprecated. -
hasSub
Checks whether the elementidexists in the SVG document.Element IDs should look like an URL fragment identifier; for example, pass
#foo(hashfoo) to get the geometry of the element that has anid="foo"attribute.- Parameters:
id- An element's id within the SVG, starting with ""(a single hash character), for example,#layer1. This notation corresponds to a URL's fragment ID.- Returns:
TRUEifidexists in the SVG document,FALSEotherwise.- Since:
- 2.22
-
internalSetTesting
public void internalSetTesting(boolean testing) Do not call this function. This is intended for librsvg's internal test suite only.- Parameters:
testing- Whether to enable testing mode
-
readStreamSync
public boolean readStreamSync(InputStream stream, @Nullable Cancellable cancellable) throws GErrorException Readsstreamand writes the data from it tohandle.Before calling this function, you may need to call
setBaseUri(java.lang.String)orsetBaseGfile(org.gnome.gio.File)to set the "base file" for resolving references to external resources. SVG elements like<image>which reference external resources will be resolved relative to the location you specify with those functions.If
cancellableis notNULL, then the operation can be cancelled by triggering the cancellable object from another thread. If the operation was cancelled, the errorG_IO_ERROR_CANCELLEDwill be returned.- Parameters:
stream- aGInputStreamcancellable- aGCancellable, orNULL- Returns:
TRUEif readingstreamsucceeded, orFALSEotherwise witherrorfilled in- Throws:
GErrorException- seeGError- Since:
- 2.32
-
renderCairo
Deprecated.Please userenderDocument(org.freedesktop.cairo.Context, org.gnome.rsvg.Rectangle)instead; that function lets you pass a viewport and obtain a good error message.Draws a loaded SVG handle to a Cairo context. Please try to userenderDocument(org.freedesktop.cairo.Context, org.gnome.rsvg.Rectangle)instead, which allows you to pick the size at which the document will be rendered.Historically this function has picked a size by itself, based on the following rules:
- If the SVG document has both
widthandheightattributes with physical units (px, in, cm, mm, pt, pc) or font-based units (em, ex), the function computes the size directly based on the dots-per-inch (DPI) you have configured withsetDpi(double). This is the same approach asgetIntrinsicSizeInPixels(org.javagi.base.Out<java.lang.Double>, org.javagi.base.Out<java.lang.Double>).
- Otherwise, if there is a
viewBoxattribute and bothwidthandheightare set to100%(or if they don't exist at all and thus default to 100%), the function uses the width and height of theviewBoxas a pixel size. This produces a rendered document with the correct aspect ratio.
- Otherwise, this function computes the extents of every graphical object in the SVG document to find the total extents. This is moderately expensive, but no more expensive than rendering the whole document, for example.
- This function cannot deal with percentage-based units for
widthandheightbecause there is no viewport against which they could be resolved; that is why it will compute the extents of objects in that case. This is why we recommend that you userenderDocument(org.freedesktop.cairo.Context, org.gnome.rsvg.Rectangle)instead, which takes in a viewport and follows the sizing policy from the web platform.
Drawing will occur with respect to the
cr'scurrent transformation: for example, if thecrhas a rotated current transformation matrix, the whole SVG will be rotated in the rendered version.This function depends on the
Handle's DPI to compute dimensions in pixels, so you should callsetDpi(double)beforehand.Note that
crmust be a Cairo context that is not in an error state, that is,cairo_status()must returnCAIRO_STATUS_SUCCESSfor it. Cairo can set a context to be in an error state in various situations, for example, if it was passed an invalid matrix or if it was created for an invalid surface.- Parameters:
cr- A Cairo context- Returns:
TRUEif drawing succeeded;FALSEotherwise. This function will emit a g_warning() if a rendering error occurs.- Since:
- 2.14
- If the SVG document has both
-
renderCairoSub
Deprecated.Please userenderLayer(org.freedesktop.cairo.Context, java.lang.String, org.gnome.rsvg.Rectangle)instead; that function lets you pass a viewport and obtain a good error message.Renders a single SVG element in the same place as for a whole SVG document (a "subset" of the document). Please try to userenderLayer(org.freedesktop.cairo.Context, java.lang.String, org.gnome.rsvg.Rectangle)instead, which allows you to pick the size at which the document with the layer will be rendered.This is equivalent to
renderCairo(org.freedesktop.cairo.Context), but it renders only a single element and its children, as if they composed an individual layer in the SVG.Historically this function has picked a size for the whole document by itself, based on the following rules:
- If the SVG document has both
widthandheightattributes with physical units (px, in, cm, mm, pt, pc) or font-based units (em, ex), the function computes the size directly based on the dots-per-inch (DPI) you have configured withsetDpi(double). This is the same approach asgetIntrinsicSizeInPixels(org.javagi.base.Out<java.lang.Double>, org.javagi.base.Out<java.lang.Double>).
- Otherwise, if there is a
viewBoxattribute and bothwidthandheightare set to100%(or if they don't exist at all and thus default to 100%), the function uses the width and height of theviewBoxas a pixel size. This produces a rendered document with the correct aspect ratio.
- Otherwise, this function computes the extents of every graphical object in the SVG document to find the total extents. This is moderately expensive, but no more expensive than rendering the whole document, for example.
- This function cannot deal with percentage-based units for
widthandheightbecause there is no viewport against which they could be resolved; that is why it will compute the extents of objects in that case. This is why we recommend that you userenderLayer(org.freedesktop.cairo.Context, java.lang.String, org.gnome.rsvg.Rectangle)instead, which takes in a viewport and follows the sizing policy from the web platform.
Drawing will occur with respect to the
cr'scurrent transformation: for example, if thecrhas a rotated current transformation matrix, the whole SVG will be rotated in the rendered version.This function depends on the
Handle's DPI to compute dimensions in pixels, so you should callsetDpi(double)beforehand.Note that
crmust be a Cairo context that is not in an error state, that is,cairo_status()must returnCAIRO_STATUS_SUCCESSfor it. Cairo can set a context to be in an error state in various situations, for example, if it was passed an invalid matrix or if it was created for an invalid surface.Element IDs should look like an URL fragment identifier; for example, pass
#foo(hashfoo) to get the geometry of the element that has anid="foo"attribute.- Parameters:
cr- A Cairo contextid- An element's id within the SVG, starting with ""(a single hash character), for example,#layer1. This notation corresponds to a URL's fragment ID. Alternatively, passNULLto render the whole SVG.- Returns:
TRUEif drawing succeeded;FALSEotherwise. This function will emit a g_warning() if a rendering error occurs.- Since:
- 2.14
- If the SVG document has both
-
renderDocument
public boolean renderDocument(org.freedesktop.cairo.Context cr, Rectangle viewport) throws GErrorException Renders the whole SVG document fitted to a viewport.The
viewportgives the position and size at which the whole SVG document will be rendered. The document is scaled proportionally to fit into this viewport.The
crmust be in aCAIRO_STATUS_SUCCESSstate, or this function will not render anything, and instead will return an error.- Parameters:
cr- A Cairo contextviewport- Viewport size at which the whole SVG would be fitted.- Returns:
TRUEon success,FALSEon error. Errors are returned in theerrorargument.API ordering: This function must be called on a fully-loaded
handle.See the section "API ordering" for details.Panics: this function will panic if the this Handle is not fully-loaded.
- Throws:
GErrorException- seeGError- Since:
- 2.46
-
renderElement
public boolean renderElement(org.freedesktop.cairo.Context cr, @Nullable String id, Rectangle elementViewport) throws GErrorException Renders a single SVG element to a given viewport.This function can be used to extract individual element subtrees and render them, scaled to a given
elementViewport.This is useful for applications which have reusable objects in an SVG and want to render them individually; for example, an SVG full of icons that are meant to be be rendered independently of each other.Element IDs should look like an URL fragment identifier; for example, pass
#foo(hashfoo) to get the geometry of the element that has anid="foo"attribute.You can pass
NULLfor theidif you want to render all the elements in the SVG, i.e. to render everything from the root element.The
element_viewportgives the position and size at which the named element will be rendered. FIXME: mention proportional scaling.- Parameters:
cr- A Cairo contextid- An element's id within the SVG, starting with ""(a single hash character), for example,#layer1. This notation corresponds to a URL's fragment ID. Alternatively, passNULLto render the whole SVG document tree.elementViewport- Viewport size in which to fit the element- Returns:
TRUEon success,FALSEon error. Errors are returned in theerrorargument.API ordering: This function must be called on a fully-loaded
handle.See the section "API ordering" for details.Panics: this function will panic if the this Handle is not fully-loaded.
- Throws:
GErrorException- seeGError- Since:
- 2.46
-
renderLayer
public boolean renderLayer(org.freedesktop.cairo.Context cr, @Nullable String id, Rectangle viewport) throws GErrorException Renders a single SVG element in the same place as for a whole SVG document.The
viewportgives the position and size at which the whole SVG document would be rendered. The document is scaled proportionally to fit into this viewport; hence the individual layer may be smaller than this.This is equivalent to
renderDocument(org.freedesktop.cairo.Context, org.gnome.rsvg.Rectangle), but it renders only a single element and its children, as if they composed an individual layer in the SVG. The element is rendered with the same transformation matrix as it has within the whole SVG document. Applications can use this to re-render a single element and repaint it on top of a previously-rendered document, for example.Element IDs should look like an URL fragment identifier; for example, pass
#foo(hashfoo) to get the geometry of the element that has anid="foo"attribute.You can pass
NULLfor theidif you want to render all the elements in the SVG, i.e. to render everything from the root element.- Parameters:
cr- A Cairo contextid- An element's id within the SVG, starting with ""(a single hash character), for example,#layer1. This notation corresponds to a URL's fragment ID. Alternatively, passNULLto render the whole SVG document tree.viewport- Viewport size at which the whole SVG would be fitted.- Returns:
TRUEon success,FALSEon error. Errors are returned in theerrorargument.API ordering: This function must be called on a fully-loaded
handle.See the section "API ordering" for details.Panics: this function will panic if the this Handle is not fully-loaded.
- Throws:
GErrorException- seeGError- Since:
- 2.46
-
setBaseGfile
Set the base URI for this Handle fromfile.Note: This function may only be called before
write(byte[])orreadStreamSync(org.gnome.gio.InputStream, org.gnome.gio.Cancellable)have been called.- Parameters:
baseFile- aGFile- Since:
- 2.32
-
setBaseUri
Set the base URI for this SVG.Note: This function may only be called before
write(byte[])orreadStreamSync(org.gnome.gio.InputStream, org.gnome.gio.Cancellable)have been called.- Parameters:
baseUri- The base uri- Since:
- 2.9
-
setCancellableForRendering
Sets a cancellable object that can be used to interrupt rendering while the handle is being rendered in another thread. For example, you can set a cancellable from your main thread, spawn a thread to do the rendering, and interrupt the rendering from the main thread by calling g_cancellable_cancel().If rendering is interrupted, the corresponding call to rsvg_handle_render_document() (or any of the other rendering functions) will return an error with domain
G_IO_ERROR, and codeG_IO_ERROR_CANCELLED.- Parameters:
cancellable- ACancellableorNULL.- Since:
- 2.59.0
-
setDpi
public void setDpi(double dpi) Sets the DPI at which the this Handle will be rendered. Common values are 75, 90, and 300 DPI.Passing a number <= 0 to
dpiwill reset the DPI to whatever the default value happens to be, but sinceRsvg.setDefaultDpi(double)is deprecated, please do not pass values <= 0 to this function.- Parameters:
dpi- Dots Per Inch (i.e. as Pixels Per Inch)- Since:
- 2.8
-
setDpiXY
public void setDpiXY(double dpiX, double dpiY) Sets the DPI at which the this Handle will be rendered. Common values are 75, 90, and 300 DPI.Passing a number <= 0 to
dpiwill reset the DPI to whatever the default value happens to be, but sinceRsvg.setDefaultDpiXY(double, double)is deprecated, please do not pass values <= 0 to this function.- Parameters:
dpiX- Dots Per Inch (i.e. Pixels Per Inch)dpiY- Dots Per Inch (i.e. Pixels Per Inch)- Since:
- 2.8
-
setSizeCallback
Deprecated.UserenderDocument(org.freedesktop.cairo.Context, org.gnome.rsvg.Rectangle)instead. This function was deprecated because when thesizeFuncis used, it makes it unclear when the librsvg functions which call thesizeFuncwill use the size computed originally, or the callback-specified size, or whether it refers to the whole SVG or to just a sub-element of it. It is easier, and unambiguous, to use code similar to the example above.Sets the sizing function for thehandle,which can be used to override the size that librsvg computes for SVG images. ThesizeFuncis called from the following functions:getDimensions(org.gnome.rsvg.DimensionData)getDimensionsSub(org.gnome.rsvg.DimensionData, java.lang.String)getPositionSub(org.gnome.rsvg.PositionData, java.lang.String)renderCairo(org.freedesktop.cairo.Context)renderCairoSub(org.freedesktop.cairo.Context, java.lang.String)
Librsvg computes the size of the SVG being rendered, and passes it to the
sizeFunc,which may then modify these values to set the final size of the generated image.- Parameters:
sizeFunc- A sizing function, orNULL
-
setStylesheet
public boolean setStylesheet(@org.jspecify.annotations.Nullable byte @Nullable [] css) throws GErrorException Sets a CSS stylesheet to use for an SVG document.The
cssLenargument is mandatory; this function will not compute the length of thecssstring. This is because a provided stylesheet, which the calling program could read from a file, can have nul characters in it.During the CSS cascade, the specified stylesheet will be used with a "User" origin.
Note that
@importrules will not be resolved, except fordata:URLs.- Parameters:
css- String with CSS data; must be valid UTF-8.- Returns:
TRUEon success,FALSEon error. Errors are returned in theerrorargument.- Throws:
GErrorException- seeGError- Since:
- 2.48
-
write
@Deprecated public boolean write(@org.jspecify.annotations.Nullable byte @Nullable [] buf) throws GErrorException Deprecated.UsereadStreamSync(org.gnome.gio.InputStream, org.gnome.gio.Cancellable)or the constructor functionsfromGfileSync(org.gnome.gio.File, java.util.Set<org.gnome.rsvg.HandleFlags>, org.gnome.gio.Cancellable)orfromStreamSync(org.gnome.gio.InputStream, org.gnome.gio.File, java.util.Set<org.gnome.rsvg.HandleFlags>, org.gnome.gio.Cancellable). This function is deprecated because it will accumulate data from thebufin memory untilclose()gets called. To avoid a big temporary buffer, use the suggested functions, which take aGFileor aGInputStreamand do not require a temporary buffer.Loads the nextcountbytes of the image. You can call this function multiple times until the whole document is consumed; then you must callclose()to actually parse the document.Before calling this function for the first time, you may need to call
setBaseUri(java.lang.String)orsetBaseGfile(org.gnome.gio.File)to set the "base file" for resolving references to external resources. SVG elements like<image>which reference external resources will be resolved relative to the location you specify with those functions.- Parameters:
buf- pointer to svg data- Returns:
TRUEon success, orFALSEon error.- Throws:
GErrorException- seeGError
-
builder
AHandle.Builderobject constructs aHandlewith the specified properties. Use the variousset...()methods to set properties, and finish construction withHandle.Builder.build().- Returns:
- the builder object
-
readStreamSync(org.gnome.gio.InputStream, org.gnome.gio.Cancellable)or the constructor functionsfromGfileSync(org.gnome.gio.File, java.util.Set<org.gnome.rsvg.HandleFlags>, org.gnome.gio.Cancellable)orfromStreamSync(org.gnome.gio.InputStream, org.gnome.gio.File, java.util.Set<org.gnome.rsvg.HandleFlags>, org.gnome.gio.Cancellable).