### JSVG ViewBox and FloatSize Management Example
Source: https://context7.com/weisj/jsvg/llms.txt
Demonstrates how to use ViewBox and FloatSize classes to control SVG rendering. It covers getting intrinsic document size, creating various ViewBox configurations, and rendering an SVG document with different viewports. Requires JSVG library and an SVG resource.
```java
import com.github.weisj.jsvg.SVGDocument;
import com.github.weisj.jsvg.parser.SVGLoader;
import com.github.weisj.jsvg.view.FloatSize;
import com.github.weisj.jsvg.view.ViewBox;
import java.awt.*;
import java.awt.geom.Point2D;
import java.awt.image.BufferedImage;
public class ViewBoxExample {
public static void main(String[] args) {
SVGLoader loader = new SVGLoader();
SVGDocument document = loader.load(ViewBoxExample.class.getResource("/icon.svg"));
// Get intrinsic document size
FloatSize intrinsicSize = document.size();
System.out.println("Intrinsic size: " + intrinsicSize.width + "x" + intrinsicSize.height);
// Get document's viewBox
ViewBox docViewBox = document.viewBox();
System.out.println("ViewBox: " + docViewBox);
// Create various ViewBox configurations
// Full canvas rendering
ViewBox fullCanvas = new ViewBox(0, 0, 400, 300);
// Offset rendering (render at position 50,50)
ViewBox offsetRender = new ViewBox(50, 50, 200, 200);
// Create from FloatSize
ViewBox fromSize = new ViewBox(new FloatSize(256, 256));
// Create from Point2D and FloatSize
ViewBox positioned = new ViewBox(new Point2D.Float(10, 10), new FloatSize(100, 100));
// Render with different viewboxes
BufferedImage canvas = new BufferedImage(500, 400, BufferedImage.TYPE_INT_ARGB);
Graphics2D g = canvas.createGraphics();
g.setColor(Color.WHITE);
g.fillRect(0, 0, 500, 400);
// Render multiple instances at different positions and sizes
document.render(null, g, new ViewBox(10, 10, 100, 100)); // Top-left, small
document.render(null, g, new ViewBox(120, 10, 150, 150)); // Top-middle, medium
document.render(null, g, new ViewBox(280, 50, 200, 200)); // Right, large
g.dispose();
// Calculate size for a specific viewport
FloatSize sizeFor100x100 = document.sizeForViewBox(new ViewBox(0, 0, 100, 100));
}
}
```
--------------------------------
### Drive SVG Animations with AnimationState in Java
Source: https://context7.com/weisj/jsvg/llms.txt
This example shows how to load an SVG document, check if it has animations, and render it with animation support using `AnimationState`. It utilizes a Swing Timer to drive the animation loop and `AwtComponentPlatformSupport` for rendering within a JPanel.
```java
import com.github.weisj.jsvg.SVGDocument;
import com.github.weisj.jsvg.parser.SVGLoader;
import com.github.weisj.jsvg.renderer.animation.AnimationState;
import com.github.weisj.jsvg.renderer.awt.AwtComponentPlatformSupport;
import com.github.weisj.jsvg.renderer.output.Output;
import com.github.weisj.jsvg.view.ViewBox;
import javax.swing.*;
import java.awt.*;
public class AnimationExample {
public static void main(String[] args) {
SVGLoader loader = new SVGLoader();
SVGDocument document = loader.load(AnimationExample.class.getResource("/animated.svg"));
// Check if document has animations
if (document.isAnimated()) {
System.out.println("Animation duration: " + document.animation().duration() + "ms");
}
JFrame frame = new JFrame("SVG Animation");
AnimatedPanel panel = new AnimatedPanel(document);
frame.setContentPane(panel);
frame.setSize(400, 400);
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.setVisible(true);
panel.startAnimation();
}
static class AnimatedPanel extends JPanel {
private final SVGDocument document;
private final long startTime;
private Timer timer;
AnimatedPanel(SVGDocument document) {
this.document = document;
this.startTime = System.currentTimeMillis();
}
void startAnimation() {
timer = new Timer(16, e -> repaint()); // ~60 FPS
timer.start();
}
void stopAnimation() {
if (timer != null) timer.stop();
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
// Create animation state with elapsed time
long currentTime = System.currentTimeMillis();
AnimationState state = new AnimationState(startTime, currentTime);
// Render with animation state
Output output = Output.createForGraphics(g2);
document.renderWithPlatform(
new AwtComponentPlatformSupport(this),
output,
new ViewBox(0, 0, getWidth(), getHeight()),
state);
output.dispose();
}
}
}
```
--------------------------------
### JSVG Custom XML Parser Configuration Example
Source: https://context7.com/weisj/jsvg/llms.txt
Illustrates how to implement a custom XML parser for advanced control over SVG loading using the `XMLInput` interface. This example configures `XMLInputFactory` properties for entity resolution and DTD support, then uses it with `SVGLoader`. Requires JSVG library and an SVG resource.
```java
import com.github.weisj.jsvg.SVGDocument;
import com.github.weisj.jsvg.parser.SVGLoader;
import com.github.weisj.jsvg.parser.LoaderContext;
import com.github.weisj.jsvg.parser.XMLInput;
import javax.xml.stream.XMLEventReader;
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLStreamException;
import java.io.InputStream;
import java.net.URI;
import java.net.URL;
public class CustomXMLParserExample {
public static void main(String[] args) throws Exception {
URL svgUrl = CustomXMLParserExample.class.getResource("/document.svg");
// Create custom XMLInputFactory with specific configuration
XMLInputFactory factory = XMLInputFactory.newFactory();
// Enable entity replacement (disabled by default in JSVG for security)
factory.setProperty(XMLInputFactory.IS_REPLACING_ENTITY_REFERENCES, true);
// Disable external DTD loading
factory.setProperty(XMLInputFactory.SUPPORT_DTD, false);
factory.setProperty(XMLInputFactory.IS_SUPPORTING_EXTERNAL_ENTITIES, false);
SVGLoader loader = new SVGLoader();
try (InputStream inputStream = svgUrl.openStream()) {
XMLInput customInput = new CustomXMLInput(factory, inputStream);
URI baseUri = svgUrl.toURI();
SVGDocument document = loader.load(
customInput,
baseUri,
LoaderContext.createDefault());
if (document != null) {
System.out.println("Loaded successfully: " + document.size());
}
}
}
static class CustomXMLInput implements XMLInput {
private final XMLInputFactory factory;
private final InputStream inputStream;
CustomXMLInput(XMLInputFactory factory, InputStream inputStream) {
this.factory = factory;
this.inputStream = inputStream;
}
@Override
public XMLEventReader createReader() throws XMLStreamException {
return factory.createXMLEventReader(inputStream);
}
}
}
```
--------------------------------
### Custom XML Parsing with XMLInputFactory in Java
Source: https://github.com/weisj/jsvg/blob/master/README.md
Shows how to implement a custom XMLInput to gain more control over the XML parsing process using a custom XMLInputFactory. This allows for specific configurations of the factory before creating an XMLEventReader. The example demonstrates loading an SVG document with a custom parser.
```java
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLEventReader;
import java.io.InputStream;
import java.net.URL;
import org.jetbrains.annotations.NotNull;
public class CustomXMLInput implements XMLInput {
private final @NotNull XMLInputFactory factory;
private final @NotNull InputStream inputStream;
private CustomXMLInput(@NotNull XMLInputFactory factory, @NotNull InputStream inputStream) {
this.factory = factory;
this.inputStream = inputStream;
}
@Override
public @NotNull XMLEventReader createReader() throws XMLStreamException {
return factory.createXMLEventReader(inputStream);
}
}
// Example usage:
// XMLInputFactory factory = XMLInputFactory.newFactory();
// // Set up the factory to your liking
// URL inputUrl = ...;
// SVGLoader loader = new SVGLoader();
// try (InputStream inputStream = inputUrl.openStream()){
// SVGDocument document = loader.load(
// new CustomXMLInput(factory,inputStream),
// inputUrl,
// LoaderContext.createDefault()
// );
// }
```
--------------------------------
### SVG Structure Example
Source: https://github.com/weisj/jsvg/blob/master/README.md
This is an example SVG structure with two rectangles, one of which has an ID 'myRect' that will be targeted for color manipulation.
```svg
```
--------------------------------
### Pre-process SVG Elements with DomProcessor in Java
Source: https://context7.com/weisj/jsvg/llms.txt
Demonstrates how to use the DomProcessor interface to modify SVG elements during the loading phase. This example shows how to dynamically override element colors based on their IDs, enabling customization before the SVG is fully parsed. It requires the jsvg library.
```java
import com.github.weisj.jsvg.SVGDocument;
import com.github.weisj.jsvg.parser.*;
import com.github.weisj.jsvg.paint.SimplePaintSVGPaint;
import java.awt.*;
import java.util.*;
public class DomProcessorExample {
public static void main(String[] args) {
// Custom processor to change colors of specific elements
ColorOverrideProcessor processor = new ColorOverrideProcessor();
processor.addColorOverride("header-rect", Color.BLUE);
processor.addColorOverride("footer-rect", Color.GREEN);
SVGLoader loader = new SVGLoader();
SVGDocument document = loader.load(
DomProcessorExample.class.getResource("/template.svg"),
LoaderContext.builder()
.preProcessor(processor)
.build());
// Later, change colors dynamically and repaint
processor.getColorPaint("header-rect").setColor(Color.RED);
}
static class ColorOverrideProcessor implements DomProcessor {
private final Map colorOverrides = new HashMap<>();
public void addColorOverride(String elementId, Color initialColor) {
colorOverrides.put(elementId, new DynamicColorPaint(initialColor));
}
public DynamicColorPaint getColorPaint(String elementId) {
return colorOverrides.get(elementId);
}
@Override
public void process(DomElement root) {
processElement(root);
root.children().forEach(this::process);
}
private void processElement(DomElement element) {
String id = element.id();
if (id != null && colorOverrides.containsKey(id)) {
DynamicColorPaint paint = colorOverrides.get(id);
String uniqueId = UUID.randomUUID().toString();
element.document().registerNamedElement(uniqueId, paint);
element.setAttribute("fill", uniqueId);
}
}
}
static class DynamicColorPaint implements SimplePaintSVGPaint {
private Color color;
DynamicColorPaint(Color color) { this.color = color; }
public void setColor(Color color) { this.color = color; }
@Override public Paint paint() { return color; }
}
}
```
--------------------------------
### Render SVG Document to BufferedImage in Java
Source: https://github.com/weisj/jsvg/blob/master/README.md
This Java code snippet illustrates how to render an SVGDocument to a BufferedImage. It obtains the SVG dimensions, creates a BufferedImage, gets a Graphics2D object, renders the SVG, and disposes of the graphics context.
```java
import com.github.weisj.jsvg.SVGDocument;
import com.github.weisj.jsvg.geometry.FloatSize;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
// ...
FloatSize size = svgDocument.size();
BufferedImage image = new BufferedImage((int) size.width,(int) size.height);
Graphics2D g = image.createGraphics();
svgDocument.render(null,g);
g.dispose();
```
--------------------------------
### Animate SVG Elements with AnimationPlayer in Java
Source: https://github.com/weisj/jsvg/blob/master/README.md
Demonstrates how to use the AnimationPlayer helper class to animate SVG elements within a Swing JComponent. It requires an SVGDocument and handles animation state updates by repainting the component. The animation can be started and stopped using dedicated methods.
```java
import javax.swing.*;
import org.jetbrains.annotations.NotNull;
public class AnimationPanel extends JComponent {
private final @NotNull SVGDocument document;
private final @NotNull AnimationPlayer player;
public AnimationPanel(@NotNull SVGDocument document) {
this.document = document;
this.player = new AnimationPlayer(e -> repaint());
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
// Setup rendering hints (see above)
// ...
document.renderWithPlatform(
new AwtComponentPlatformSupport(this),
Output.createForGraphics((Graphics2D) g),
new ViewBox(0, 0, getWidth(), getHeight()),
animationPlayer.animationState());
}
public void startAnimation() {
player.start();
}
public void stopAnimation() {
player.stop();
}
}
```
--------------------------------
### Extract SVG as Java Shape using computeShape()
Source: https://context7.com/weisj/jsvg/llms.txt
This example demonstrates how to convert an SVG document into a Java `Shape` object using the `computeShape()` method. The resulting `Area` object can be used for hit testing, performing path operations, or custom rendering with different styles. An optional `ViewBox` can be provided to control the coordinate space.
```java
import com.github.weisj.jsvg.SVGDocument;
import com.github.weisj.jsvg.parser.SVGLoader;
import com.github.weisj.jsvg.view.ViewBox;
import java.awt.*;
import java.awt.geom.AffineTransform;
import java.awt.geom.Area;
import java.awt.geom.Point2D;
import java.awt.image.BufferedImage;
public class ShapeExtractionExample {
public static void main(String[] args) {
SVGLoader loader = new SVGLoader();
SVGDocument document = loader.load(ShapeExtractionExample.class.getResource("/icon.svg"));
// Extract shape at original size
Shape originalShape = document.computeShape();
// Extract shape scaled to specific bounds
Shape scaledShape = document.computeShape(new ViewBox(0, 0, 100, 100));
// Use shape for hit testing
Point2D clickPoint = new Point2D.Double(50, 50);
boolean isInside = scaledShape.contains(clickPoint);
System.out.println("Click inside shape: " + isInside);
// Use shape for custom rendering with different styles
BufferedImage image = new BufferedImage(200, 200, BufferedImage.TYPE_INT_ARGB);
Graphics2D g = image.createGraphics();
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
// Translate and render with custom fill
g.translate(50, 50);
g.setColor(new Color(0, 120, 200));
g.fill(scaledShape);
// Render outline with custom stroke
g.setColor(Color.DARK_GRAY);
g.setStroke(new BasicStroke(2f));
g.draw(scaledShape);
g.dispose();
// Combine with other shapes using Area operations
Area combined = new Area(scaledShape);
combined.intersect(new Area(new Rectangle(25, 25, 50, 50)));
}
}
```
--------------------------------
### Configure Nightly Snapshot Builds in Gradle
Source: https://github.com/weisj/jsvg/blob/master/README.md
This code snippet configures a Gradle project to use nightly snapshot builds of JSVG from Sonatype. It includes setting up the repository and resolving changing modules for the latest integration builds.
```kotlin
repositories {
maven {
url = uri("https://central.sonatype.com/repository/maven-snapshots")
}
}
// Optional:
configurations.all {
resolutionStrategy.cacheChangingModulesFor(0, "seconds")
}
dependencies {
implementation("com.github.weisj:jsvg:latest.integration")
}
```
--------------------------------
### UI Integration for Dynamic Color Change (Java)
Source: https://github.com/weisj/jsvg/blob/master/README.md
Integrates the dynamic color functionality into a UI. It retrieves the DynamicAWTSvgPaint instance, sets up an SVGPanel, and adds a button to allow users to select and apply new colors, repainting the panel to reflect changes.
```java
DynamicAWTSvgPaint dynamicColor = processor.customColorForId("myRect");
SVGPanel panel = new SVGPanel(document);
JButton button = new JButton("Change color");
button.addActionListener(e -> {
Color newColor = JColorChooser.showDialog(panel, "Choose a color", dynamicColor.color());
if (newColor != null) {
dynamicColor.setColor(newColor);
panel.repaint();
}
});
JPanel content = new JPanel(new BorderLayout());
content.add(panel, BorderLayout.CENTER);
content.add(button, BorderLayout.SOUTH);
frame.setContentPane(content);
```
--------------------------------
### Load SVG Documents with SVGLoader in Java
Source: https://context7.com/weisj/jsvg/llms.txt
Demonstrates how to load SVG documents using the SVGLoader class in Java. It covers basic loading from URLs, advanced configuration with LoaderContext for resource policies, and loading from InputStreams with a base URI for relative resource resolution. The SVGLoader is not thread-safe.
```java
import com.github.weisj.jsvg.SVGDocument;
import com.github.weisj.jsvg.parser.SVGLoader;
import com.github.weisj.jsvg.parser.LoaderContext;
import com.github.weisj.jsvg.parser.resources.ResourcePolicy;
import java.net.URL;
import java.io.InputStream;
import java.net.URI;
public class LoadingExample {
public static void main(String[] args) throws Exception {
SVGLoader loader = new SVGLoader();
// Basic loading from URL
URL svgUrl = LoadingExample.class.getResource("/icons/logo.svg");
SVGDocument document = loader.load(svgUrl);
// Loading with custom configuration
SVGDocument secureDocument = loader.load(svgUrl,
LoaderContext.builder()
.externalResourcePolicy(ResourcePolicy.DENY_EXTERNAL)
.build());
// Loading from InputStream with base URI for relative resource resolution
try (InputStream is = LoadingExample.class.getResourceAsStream("/icons/complex.svg")) {
URI baseUri = LoadingExample.class.getResource("/icons/").toURI();
SVGDocument streamDocument = loader.load(is, baseUri,
LoaderContext.builder()
.externalResourcePolicy(ResourcePolicy.ALLOW_RELATIVE)
.build());
}
// Check document properties
if (document != null) {
System.out.println("Size: " + document.size().width + "x" + document.size().height);
System.out.println("Animated: " + document.isAnimated());
}
}
}
```
--------------------------------
### Control External Resource Loading with ResourcePolicy in Java
Source: https://context7.com/weisj/jsvg/llms.txt
Illustrates how to configure the ResourcePolicy in JSVG to manage external resource loading, such as images and fonts. It showcases different policy levels (DENY_ALL, DENY_EXTERNAL, ALLOW_RELATIVE, ALLOW_ALL) for security and flexibility when parsing SVG documents. Requires the jsvg library.
```java
import com.github.weisj.jsvg.SVGDocument;
import com.github.weisj.jsvg.parser.SVGLoader;
import com.github.weisj.jsvg.parser.LoaderContext;
import com.github.weisj.jsvg.parser.resources.ResourcePolicy;
import java.net.URI;
import java.net.URL;
public class ResourcePolicyExample {
public static void main(String[] args) throws Exception {
SVGLoader loader = new SVGLoader();
URL svgUrl = ResourcePolicyExample.class.getResource("/document.svg");
// DENY_ALL: No external resources, no embedded data URIs
SVGDocument strictDoc = loader.load(svgUrl,
LoaderContext.builder()
.externalResourcePolicy(ResourcePolicy.DENY_ALL)
.build());
// DENY_EXTERNAL: Allow embedded data URIs (data:image/png;base64,...)
// but block external file/http references
SVGDocument dataUriDoc = loader.load(svgUrl,
LoaderContext.builder()
.externalResourcePolicy(ResourcePolicy.DENY_EXTERNAL)
.build());
// ALLOW_RELATIVE: Allow resources relative to the document's base URI
// Good for SVGs that reference local assets in the same directory
SVGDocument relativeDoc = loader.load(svgUrl,
LoaderContext.builder()
.externalResourcePolicy(ResourcePolicy.ALLOW_RELATIVE)
.build());
// ALLOW_ALL: Allow all resources including absolute paths and remote URLs
// Only use for fully trusted content
SVGDocument trustedDoc = loader.load(svgUrl,
LoaderContext.builder()
.externalResourcePolicy(ResourcePolicy.ALLOW_ALL)
.build());
}
}
```
--------------------------------
### SVGDocument.render() - Rendering to Graphics2D
Source: https://context7.com/weisj/jsvg/llms.txt
The `SVGDocument.render()` method allows you to render an SVG document to any `Graphics2D` context. This includes rendering to `BufferedImage`, Swing components, or PDF generators. You can control the rendering area and scale using `ViewBox`. Passing a `Component` enables platform-specific font resolution, while `null` is used for standalone rendering.
```APIDOC
## SVGDocument.render()
### Description
Renders the SVG document to a `Graphics2D` context. Supports rendering to various contexts like `BufferedImage`, Swing components, and PDF generators. Allows control over rendering area and scaling via `ViewBox`. Platform-specific font resolution is enabled by passing a `Component`; `null` is used for standalone rendering.
### Method
`public void render(java.awt.Component component, java.awt.Graphics2D g)`
`public void render(java.awt.Component component, java.awt.Graphics2D g, com.github.weisj.jsvg.view.ViewBox viewBox)`
### Endpoint
N/A (This is a Java method)
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
None
### Request Example
```java
// Example usage within a Java application
import com.github.weisj.jsvg.SVGDocument;
import com.github.weisj.jsvg.parser.SVGLoader;
import com.github.weisj.jsvg.view.ViewBox;
import com.github.weisj.jsvg.view.FloatSize;
import javax.swing.*;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import javax.imageio.ImageIO;
public class RenderingExample {
public static void main(String[] args) throws Exception {
SVGLoader loader = new SVGLoader();
SVGDocument document = loader.load(RenderingExample.class.getResource("/logo.svg"));
// Render to BufferedImage at original size
FloatSize size = document.size();
BufferedImage image = new BufferedImage(
(int) size.width,
(int) size.height,
BufferedImage.TYPE_INT_ARGB);
Graphics2D g = image.createGraphics();
document.render(null, g);
g.dispose();
ImageIO.write(image, "PNG", new File("output.png"));
// Render scaled to specific dimensions
BufferedImage scaledImage = new BufferedImage(200, 200, BufferedImage.TYPE_INT_ARGB);
Graphics2D g2 = scaledImage.createGraphics();
document.render(null, g2, new ViewBox(0, 0, 200, 200));
g2.dispose();
// Render in Swing component with proper platform support
JFrame frame = new JFrame("SVG Viewer");
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.setContentPane(new JPanel() {
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
document.render(this, (Graphics2D) g, new ViewBox(0, 0, getWidth(), getHeight()));
}
});
frame.setSize(400, 400);
frame.setVisible(true);
}
}
```
### Response
#### Success Response (void)
This method does not return a value. Rendering is performed directly onto the provided `Graphics2D` context.
#### Response Example
N/A
```
--------------------------------
### Load SVG Document with LoaderContext in Java
Source: https://github.com/weisj/jsvg/blob/master/README.md
This Java code shows how to load an SVG document with more control by providing a custom LoaderContext to the SVGLoader. The LoaderContext allows for configuration of the loading process.
```java
import com.github.weisj.jsvg.parser.SVGLoader;
import com.github.weisj.jsvg.SVGDocument;
import com.github.weisj.jsvg.parser.SVGLoader.LoaderContext;
import java.net.URL;
// ...
SVGLoader loader = new SVGLoader();
URL svgUrl = MyClass.class.getResource("mySvgFile.svg");
SVGDocument svgDocument = loader.load(svgUrl,
LoaderContext.builder()
// configure the context
// ...
.build());
```
--------------------------------
### Enable Image Anti-aliasing with SVGRenderingHints in Java
Source: https://github.com/weisj/jsvg/blob/master/README.md
Sets a custom SVG-specific rendering hint to enable anti-aliasing for images. This utilizes the SVGRenderingHints class and defaults to the value of RenderingHints.KEY_ANTIALIASING if not explicitly provided.
```java
// Will use the value of RenderingHints.KEY_ANTIALIASING by default
g.setRenderingHint(SVGRenderingHints.KEY_IMAGE_ANTIALIASING, SVGRenderingHints.VALUE_IMAGE_ANTIALIASING_ON);
```
--------------------------------
### Set Rendering Hints for Anti-aliasing and Stroke Control in Java
Source: https://github.com/weisj/jsvg/blob/master/README.md
Configures the Graphics2D object to enable anti-aliasing and pure stroke control for improved rendering quality. These settings are automatically applied by JSVG if not explicitly set.
```java
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, RenderingHints.VALUE_STROKE_PURE);
```
--------------------------------
### Load SVG Document using SVGLoader in Java
Source: https://github.com/weisj/jsvg/blob/master/README.md
This Java code demonstrates how to load an SVG file into an SVGDocument using the SVGLoader class. It requires a URL to the SVG resource and returns an SVGDocument object.
```java
import com.github.weisj.jsvg.parser.SVGLoader;
import com.github.weisj.jsvg.SVGDocument;
import java.net.URL;
// ...
SVGLoader loader = new SVGLoader();
URL svgUrl = MyClass.class.getResource("mySvgFile.svg");
SVGDocument svgDocument = loader.load(svgUrl);
```
--------------------------------
### Render SVG to Swing Component (Java)
Source: https://github.com/weisj/jsvg/blob/master/README.md
This Java code demonstrates how to load an SVG file using SVGLoader and render it onto a JPanel within a JFrame. It requires the JSVG library and standard Java Swing components. The output is a visible Swing window displaying the SVG.
```java
import javax.swing.*;
import java.awt.*;
import java.net.URL;
import com.github.weisj.jsvg.*;
import com.github.weisj.jsvg.attributes.*;
import com.github.weisj.jsvg.parser.*;
import org.jetbrains.annotations.NotNull;
import java.util.Objects;
public class RenderExample {
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
SVGLoader loader = new SVGLoader();
URL svgUrl = RenderExample.class.getResource("path/to/image.svg");
SVGDocument document = loader.load(Objects.requireNonNull(svgUrl, "SVG file not found"));
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.setPreferredSize(new Dimension(400, 400));
frame.setContentPane(new SVGPanel(Objects.requireNonNull(document)));
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
});
}
static class SVGPanel extends JPanel {
private @NotNull final SVGDocument document;
SVGPanel(@NotNull SVGDocument document) {
this.document = document;
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
((Graphics2D) g).setRenderingHint(
RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
((Graphics2D) g).setRenderingHint(
RenderingHints.KEY_STROKE_CONTROL,
RenderingHints.VALUE_STROKE_PURE);
document.render(this, (Graphics2D) g, new ViewBox(0, 0, getWidth(), getHeight()));
}
}
}
```
--------------------------------
### Add JSVG Dependency to Gradle Project
Source: https://github.com/weisj/jsvg/blob/master/README.md
This code snippet shows how to add the JSVG library as a dependency to a Gradle project using Maven Central. It specifies the implementation artifact and version.
```kotlin
dependencies {
implementation("com.github.weisj:jsvg:2.0.0")
}
```
--------------------------------
### Loading SVG with Custom Pre-processor (Java)
Source: https://github.com/weisj/jsvg/blob/master/README.md
Loads an SVG document using a custom DomProcessor for pre-processing. The CustomColorsProcessor is provided to modify SVG element attributes before parsing.
```java
CustomColorsProcessor processor = new CustomColorsProcessor(List.of("myRect"));
document = loader.load(svgUrl, LoaderContext.builder().preProcessor(processor).build());
```
--------------------------------
### SVGRenderingHints - Custom Rendering Quality
Source: https://context7.com/weisj/jsvg/llms.txt
JSVG allows for fine-grained control over rendering quality using `SVGRenderingHints`, which extend standard AWT `RenderingHints`. These hints can be applied to the `Graphics2D` context before rendering to control aspects like antialiasing, soft clipping, mask rendering, and offscreen image caching. JSVG automatically applies default hints for optimal quality if none are specified.
```APIDOC
## SVGRenderingHints
### Description
Provides custom rendering hints for JSVG to control image antialiasing, soft clipping, mask rendering, and offscreen image caching. These hints extend standard AWT `RenderingHints` and can be set on the `Graphics2D` context prior to rendering. JSVG applies default rendering hints for optimal quality if not explicitly set.
### Method
`graphics2D.setRenderingHint(java.awt.RenderingHints.Key key, Object value)`
### Endpoint
N/A (This is a Java class for setting rendering hints)
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
None
### Request Example
```java
import com.github.weisj.jsvg.SVGDocument;
import com.github.weisj.jsvg.parser.SVGLoader;
import com.github.weisj.jsvg.renderer.SVGRenderingHints;
import com.github.weisj.jsvg.view.ViewBox;
import java.awt.*;
import java.awt.image.BufferedImage;
public class RenderingHintsExample {
public static void main(String[] args) {
SVGLoader loader = new SVGLoader();
SVGDocument document = loader.load(RenderingHintsExample.class.getResource("/icon.svg"));
BufferedImage image = new BufferedImage(256, 256, BufferedImage.TYPE_INT_ARGB);
Graphics2D g = image.createGraphics();
// Standard AWT hints (JSVG sets these automatically if not specified)
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, RenderingHints.VALUE_STROKE_PURE);
// JSVG-specific hints
// Enable antialiasing for embedded images
g.setRenderingHint(SVGRenderingHints.KEY_IMAGE_ANTIALIASING,
SVGRenderingHints.VALUE_IMAGE_ANTIALIASING_ON);
// Enable soft (anti-aliased) clipping for clipPath elements
g.setRenderingHint(SVGRenderingHints.KEY_SOFT_CLIPPING,
SVGRenderingHints.VALUE_SOFT_CLIPPING_ON);
// Accurate mask/clip rendering (slower but more precise)
g.setRenderingHint(SVGRenderingHints.KEY_MASK_CLIP_RENDERING,
SVGRenderingHints.VALUE_MASK_CLIP_RENDERING_ACCURACY);
// Disable offscreen image caching to reduce memory usage
g.setRenderingHint(SVGRenderingHints.KEY_CACHE_OFFSCREEN_IMAGE,
SVGRenderingHints.VALUE_NO_CACHE);
document.render(null, g, new ViewBox(0, 0, 256, 256));
g.dispose();
}
}
```
### Response
#### Success Response (void)
Setting rendering hints modifies the `Graphics2D` context. The rendering process itself does not return a specific value related to the hints.
#### Response Example
N/A
```
--------------------------------
### Render SVG to Graphics2D in Java
Source: https://context7.com/weisj/jsvg/llms.txt
Renders an SVG document to a Graphics2D context, which can be a BufferedImage, Swing component, or PDF generator. It supports platform-specific font resolution via a Component and allows scaling and area control using ViewBox. JSVG automatically applies optimal rendering hints if none are provided.
```java
import com.github.weisj.jsvg.SVGDocument;
import com.github.weisj.jsvg.parser.SVGLoader;
import com.github.weisj.jsvg.view.ViewBox;
import com.github.weisj.jsvg.view.FloatSize;
import javax.swing.*;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import javax.imageio.ImageIO;
public class RenderingExample {
public static void main(String[] args) throws Exception {
SVGLoader loader = new SVGLoader();
SVGDocument document = loader.load(RenderingExample.class.getResource("/logo.svg"));
// Render to BufferedImage at original size
FloatSize size = document.size();
BufferedImage image = new BufferedImage(
(int) size.width,
(int) size.height,
BufferedImage.TYPE_INT_ARGB);
Graphics2D g = image.createGraphics();
document.render(null, g);
g.dispose();
ImageIO.write(image, "PNG", new File("output.png"));
// Render scaled to specific dimensions
BufferedImage scaledImage = new BufferedImage(200, 200, BufferedImage.TYPE_INT_ARGB);
Graphics2D g2 = scaledImage.createGraphics();
document.render(null, g2, new ViewBox(0, 0, 200, 200));
g2.dispose();
// Render in Swing component with proper platform support
JFrame frame = new JFrame("SVG Viewer");
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.setContentPane(new JPanel() {
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
document.render(this, (Graphics2D) g, new ViewBox(0, 0, getWidth(), getHeight()));
}
});
frame.setSize(400, 400);
frame.setVisible(true);
}
}
```
--------------------------------
### Render SVG Document to JComponent in Java
Source: https://github.com/weisj/jsvg/blob/master/README.md
This Java code shows how to render an SVGDocument within a Swing JComponent by overriding the paintComponent method. It uses the SVGDocument's render method with a ViewBox to fit the component's dimensions.
```java
import com.github.weisj.jsvg.SVGDocument;
import com.github.weisj.jsvg.viewbox.ViewBox;
import java.awt.Graphics;
import java.awt.Graphics2D;
import javax.swing.JComponent;
// ...
class MyComponent extends JComponent {
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
svgDocument.render(this, (Graphics2D) g, new ViewBox(0, 0, getWidth(), getHeight()));
}
}
```
--------------------------------
### Custom Color Processing Logic (Java)
Source: https://github.com/weisj/jsvg/blob/master/README.md
Implements a DomProcessor to dynamically change the fill color of specified SVG elements. It identifies elements by ID, parses their current fill color, and registers a DynamicAWTSvgPaint instance to manage the color changes.
```java
class CustomColorsProcessor implements DomProcessor {
private final Map customColors = new HashMap<>();
public CustomColorsProcessor(@NotNull List elementIds) {
for (String elementId : elementIds) {
customColors.put(elementId, new DynamicAWTSvgPaint(Color.BLACK));
}
}
@Nullable DynamicAWTSvgPaint customColorForId(@NotNull String id) {
return customColors.get(id);
}
@Override
public void process(@NotNull DomElement root) {
processImpl(root);
root.children().forEach(this::process);
}
private void processImpl(@NotNull DomElement element) {
String nodeId = element.id();
if (customColors.containsKey(nodeId)) {
DynamicAWTSvgPaint dynamicColor = customColors.get(nodeId);
Color color = element.document().loaderContext().paintParser()
.parseColor(element.attribute("fill", "black"));
if (color == null) color = Color.BLACK;
dynamicColor.setColor(color);
String uniqueIdForDynamicColor = UUID.randomUUID().toString();
element.document().registerNamedElement(uniqueIdForDynamicColor, dynamicColor);
element.setAttribute("fill", uniqueIdForDynamicColor);
}
}
}
class DynamicAWTSvgPaint implements SimplePaintSVGPaint {
private @NotNull Color color;
DynamicAWTSvgPaint(@NotNull Color color) {
this.color = color;
}
public void setColor(@NotNull Color color) {
this.color = color;
}
public @NotNull Color color() {
return color;
}
@Override
public @NotNull Paint paint() {
return color;
}
}
```
--------------------------------
### Enable Soft Clipping with SVGRenderingHints in Java
Source: https://github.com/weisj/jsvg/blob/master/README.md
Enables soft clipping (anti-aliasing along the edges of the clip shape) when using a element. This setting is controlled via SVGRenderingHints and is planned to be enabled by default in future versions.
```java
g.setRenderingHint(SVGRenderingHints.KEY_SOFT_CLIPPING, SVGRenderingHints.VALUE_SOFT_CLIPPING_ON);
```
--------------------------------
### Customize SVG Rendering Quality with SVGRenderingHints in Java
Source: https://context7.com/weisj/jsvg/llms.txt
Utilizes JSVG's `SVGRenderingHints` to control rendering aspects like antialiasing, soft clipping, mask rendering, and offscreen image caching. These hints extend standard AWT `RenderingHints` and are applied to the `Graphics2D` context before rendering. Default JSVG settings provide good quality out-of-the-box.
```java
import com.github.weisj.jsvg.SVGDocument;
import com.github.weisj.jsvg.parser.SVGLoader;
import com.github.weisj.jsvg.renderer.SVGRenderingHints;
import com.github.weisj.jsvg.view.ViewBox;
import java.awt.*;
import java.awt.image.BufferedImage;
public class RenderingHintsExample {
public static void main(String[] args) {
SVGLoader loader = new SVGLoader();
SVGDocument document = loader.load(RenderingHintsExample.class.getResource("/icon.svg"));
BufferedImage image = new BufferedImage(256, 256, BufferedImage.TYPE_INT_ARGB);
Graphics2D g = image.createGraphics();
// Standard AWT hints (JSVG sets these automatically if not specified)
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, RenderingHints.VALUE_STROKE_PURE);
// JSVG-specific hints
// Enable antialiasing for embedded images
g.setRenderingHint(SVGRenderingHints.KEY_IMAGE_ANTIALIASING,
SVGRenderingHints.VALUE_IMAGE_ANTIALIASING_ON);
// Enable soft (anti-aliased) clipping for clipPath elements
g.setRenderingHint(SVGRenderingHints.KEY_SOFT_CLIPPING,
SVGRenderingHints.VALUE_SOFT_CLIPPING_ON);
// Accurate mask/clip rendering (slower but more precise)
g.setRenderingHint(SVGRenderingHints.KEY_MASK_CLIP_RENDERING,
SVGRenderingHints.VALUE_MASK_CLIP_RENDERING_ACCURACY);
// Disable offscreen image caching to reduce memory usage
g.setRenderingHint(SVGRenderingHints.KEY_CACHE_OFFSCREEN_IMAGE,
SVGRenderingHints.VALUE_NO_CACHE);
document.render(null, g, new ViewBox(0, 0, 256, 256));
g.dispose();
}
}
```
=== COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.