Class SVGGraphics2D

  • All Implemented Interfaces:
    java.lang.Cloneable, XMLConstants, ErrorConstants, SVGSyntax, CSSConstants, SVGConstants

    public class SVGGraphics2D
    extends AbstractGraphics2D
    implements java.lang.Cloneable, SVGSyntax, ErrorConstants
    This implementation of the java.awt.Graphics2D abstract class allows users to generate SVG (Scalable Vector Graphics) content from Java code. SVGGraphics2D generates a DOM tree whose root is obtained through the getRoot method. Refer to the DOMTreeManager and DOMGroupManager documentation for details on the structure of the generated DOM tree. The SVGGraphics2D class can produce a DOM tree using any implementation that conforms to the W3C DOM 1.0 specification (see http://www.w3.org). At construction time, the SVGGraphics2D must be given a org.w3.dom.Document instance that is used as a factory to create the various nodes in the DOM tree it generates. The various graphic context attributes (e.g., AffineTransform, Paint) are managed by a GraphicContext object.
    Version:
    $Id: SVGGraphics2D.java 1808021 2017-09-11 12:17:28Z ssteiner $
    See Also:
    GraphicContext, DOMTreeManager, DOMGroupManager, ImageHandler, ExtensionHandler, Document
    • Field Detail

      • DEFAULT_XML_ENCODING

        public static final java.lang.String DEFAULT_XML_ENCODING
        See Also:
        Constant Field Values
      • DEFAULT_MAX_GC_OVERRIDES

        public static final int DEFAULT_MAX_GC_OVERRIDES
        Controls the policy for grouping nodes. Once the number of attributes overridden by a child element is greater than DEFAULT_MAX_GC_OVERRIDES, a new group is created.
        See Also:
        DOMTreeManager, Constant Field Values
      • domTreeManager

        protected DOMTreeManager domTreeManager
        The DOMTreeManager manages the process of creating and growing the SVG tree. This SVGGraphics2D relies on the DOMTreeManager to process attributes based on the GraphicContext state and create groups when needed.
      • domGroupManager

        protected DOMGroupManager domGroupManager
        The DOMGroupManager manages additions to the current group node associated for this Graphics2D object. Once a group is complete, the group manager appends it to the DOM tree through the DOMTreeManager. Note that each SVGGraphics2D instance has its own DOMGroupManager (i.e., its own current group) but that all SVGGraphics2D originating from the same SVGGraphics2D through various createGraphics calls share the same DOMTreeManager.
      • generatorCtx

        protected SVGGeneratorContext generatorCtx
        Contains some information for SVG generation.
      • shapeConverter

        protected SVGShape shapeConverter
        Used to convert Java 2D API Shape objects to equivalent SVG elements
      • svgCanvasSize

        protected java.awt.Dimension svgCanvasSize
        SVG Canvas size
      • fmg

        protected java.awt.Graphics2D fmg
        Used to create proper font metrics
      • unsupportedAttributes

        protected java.util.Set unsupportedAttributes
    • Constructor Detail

      • SVGGraphics2D

        public SVGGraphics2D​(org.w3c.dom.Document domFactory)
        Parameters:
        domFactory - Factory which will produce Elements for the DOM tree this Graphics2D generates.
        Throws:
        SVGGraphics2DRuntimeException - if domFactory is null.
      • SVGGraphics2D

        public SVGGraphics2D​(org.w3c.dom.Document domFactory,
                             ImageHandler imageHandler,
                             ExtensionHandler extensionHandler,
                             boolean textAsShapes)
        Parameters:
        domFactory - Factory which will produce Elements for the DOM tree this Graphics2D generates.
        imageHandler - defines how images are referenced in the generated SVG fragment
        extensionHandler - defines how Java 2D API extensions map to SVG Nodes.
        textAsShapes - if true, all text is turned into SVG shapes in the convertion. No SVG text is output.
        Throws:
        SVGGraphics2DRuntimeException - if domFactory is null.
      • SVGGraphics2D

        public SVGGraphics2D​(SVGGeneratorContext generatorCtx,
                             boolean textAsShapes)
        Creates a new SVGGraphics2D object.
        Parameters:
        generatorCtx - the SVGGeneratorContext instance that will provide all useful information to the generator.
        textAsShapes - if true, all text is turned into SVG shapes in the convertion. No SVG text is output.
        Throws:
        SVGGraphics2DRuntimeException - if generatorContext is null.
      • SVGGraphics2D

        public SVGGraphics2D​(SVGGraphics2D g)
        This constructor is used in create()
        See Also:
        create()
    • Method Detail

      • getSVGCanvasSize

        public final java.awt.Dimension getSVGCanvasSize()
        Returns:
        SVG Canvas size, as set in the root svg element
      • setSVGCanvasSize

        public final void setSVGCanvasSize​(java.awt.Dimension svgCanvasSize)
        Set the Canvas size, this is used to set the width and height attributes on the outermost 'svg' element.
        Parameters:
        svgCanvasSize - SVG Canvas size. May be null (equivalent to 100%, 100%)
      • getGeneratorContext

        public final SVGGeneratorContext getGeneratorContext()
        Returns:
        the SVGGeneratorContext used by this SVGGraphics2D instance.
      • getShapeConverter

        public final SVGShape getShapeConverter()
        Returns:
        the SVGShape used by this SVGGraphics2D instance to turn Java2D shapes into SVG Shape objects.
      • getDOMTreeManager

        public final DOMTreeManager getDOMTreeManager()
        Returns:
        the DOMTreeManager used by this SVGGraphics2D instance
      • setDOMTreeManager

        protected final void setDOMTreeManager​(DOMTreeManager treeMgr)
        Set a DOM Tree manager for the SVGGraphics2D.
        Parameters:
        treeMgr - the new DOM Tree manager this SVGGraphics2D should use
      • getDOMGroupManager

        protected final DOMGroupManager getDOMGroupManager()
        Returns:
        the DOMGroupManager used by this SVGGraphics2D instance
      • setDOMGroupManager

        protected final void setDOMGroupManager​(DOMGroupManager groupMgr)
        Set a new DOM Group manager for this SVGGraphics2D.
        Parameters:
        groupMgr - the new DOM Group manager this SVGGraphics2D should use
      • getDOMFactory

        public final org.w3c.dom.Document getDOMFactory()
        Returns:
        the Document used as a DOM object factory by this SVGGraphics2D instance
      • getImageHandler

        public final ImageHandler getImageHandler()
        Returns:
        the ImageHandler used by this SVGGraphics2D instance
      • getGenericImageHandler

        public final GenericImageHandler getGenericImageHandler()
        Returns:
        the GenericImageHandler used by this SVGGraphics2D instance
      • getExtensionHandler

        public final ExtensionHandler getExtensionHandler()
        Returns:
        the extension handler used by this SVGGraphics2D instance
      • setExtensionHandler

        public final void setExtensionHandler​(ExtensionHandler extensionHandler)
        Parameters:
        extensionHandler - new extension handler this SVGGraphics2D should use
      • buildSVGGeneratorContext

        public static SVGGeneratorContext buildSVGGeneratorContext​(org.w3c.dom.Document domFactory,
                                                                   ImageHandler imageHandler,
                                                                   ExtensionHandler extensionHandler)
        Helper method to create an SVGGeneratorContext from the constructor parameters.
      • setGeneratorContext

        protected void setGeneratorContext​(SVGGeneratorContext generatorCtx)
        Sets an non null SVGGeneratorContext.
      • stream

        public void stream​(java.lang.String svgFileName,
                           boolean useCss)
                    throws SVGGraphics2DIOException
        Parameters:
        svgFileName - name of the file where SVG content should be written
        useCss - defines whether the output SVG should use CSS style properties as opposed to plain attributes.
        Throws:
        SVGGraphics2DIOException
      • stream

        public void stream​(java.io.Writer writer,
                           boolean useCss,
                           boolean escaped)
                    throws SVGGraphics2DIOException
        Parameters:
        writer - used to writer out the SVG content
        useCss - defines whether the output SVG should use CSS
        escaped - defines if the characters will be escaped style properties as opposed to plain attributes.
        Throws:
        SVGGraphics2DIOException
      • stream

        public void stream​(java.io.Writer writer,
                           boolean useCss)
                    throws SVGGraphics2DIOException
        Parameters:
        writer - used to writer out the SVG content
        useCss - defines whether the output SVG should use CSS style properties as opposed to plain attributes.
        Throws:
        SVGGraphics2DIOException
      • stream

        public void stream​(org.w3c.dom.Element svgRoot,
                           java.io.Writer writer,
                           boolean useCss,
                           boolean escaped)
                    throws SVGGraphics2DIOException
        Parameters:
        svgRoot - root element to stream out
        writer - output
        useCss - defines whether the output SVG should use CSS style
        escaped - defines if the characters will be escaped properties as opposed to plain attributes.
        Throws:
        SVGGraphics2DIOException
      • getDefinitionSet

        public java.util.List getDefinitionSet()
        Invoking this method will return a set of definition element that contain all the definitions referenced by the attributes generated by the various converters. This also resets the converters.
      • getTopLevelGroup

        public org.w3c.dom.Element getTopLevelGroup()
        Invoking this method will return a reference to the topLevelGroup Element managed by this object. It will also cause this object to start working with a new topLevelGroup.
        Returns:
        top level group
      • getTopLevelGroup

        public org.w3c.dom.Element getTopLevelGroup​(boolean includeDefinitionSet)
        Invoking this method will return a reference to the topLevelGroup Element managed by this object. It will also cause this object to start working with a new topLevelGroup.
        Parameters:
        includeDefinitionSet - if true, the definition set is included and the converters are reset (i.e., they start with an empty set of definitions).
        Returns:
        top level group
      • setTopLevelGroup

        public void setTopLevelGroup​(org.w3c.dom.Element topLevelGroup)
        Sets the topLevelGroup to the input element. This will throw an exception if the input element is not of type 'g' or if it is null.
      • getRoot

        public org.w3c.dom.Element getRoot()
        Returns:
        the svg root node of the SVG document associated with this object
      • getRoot

        public org.w3c.dom.Element getRoot​(org.w3c.dom.Element svgRoot)
        This version of the getRoot method will append the input svgRoot and set its attributes.
        Parameters:
        svgRoot - an SVG element underwhich the content should be appended.
        Returns:
        the svg root node of the SVG document associated with this object.
      • create

        public java.awt.Graphics create()
        Creates a new Graphics object that is a copy of this Graphics object.
        Specified by:
        create in class java.awt.Graphics
        Returns:
        a new graphics context that is a copy of this graphics context.
      • setXORMode

        public void setXORMode​(java.awt.Color c1)
        Sets the paint mode of this graphics context to alternate between this graphics context's current color and the new specified color. This specifies that logical pixel operations are performed in the XOR mode, which alternates pixels between the current color and a specified XOR color.

        When drawing operations are performed, pixels which are the current color are changed to the specified color, and vice versa.

        Pixels that are of colors other than those two colors are changed in an unpredictable but reversible manner; if the same figure is drawn twice, then all pixels are restored to their original values.

        Specified by:
        setXORMode in class java.awt.Graphics
        Parameters:
        c1 - the XOR alternation color
      • getFontMetrics

        public java.awt.FontMetrics getFontMetrics​(java.awt.Font f)
        Gets the font metrics for the specified font.
        Specified by:
        getFontMetrics in class java.awt.Graphics
        Parameters:
        f - the specified font
        Returns:
        the font metrics for the specified font.
        See Also:
        Graphics.getFont(), FontMetrics, Graphics.getFontMetrics()
      • copyArea

        public void copyArea​(int x,
                             int y,
                             int width,
                             int height,
                             int dx,
                             int dy)
        Copies an area of the component by a distance specified by dx and dy. From the point specified by x and y, this method copies downwards and to the right. To copy an area of the component to the left or upwards, specify a negative value for dx or dy. If a portion of the source rectangle lies outside the bounds of the component, or is obscured by another window or component, copyArea will be unable to copy the associated pixels. The area that is omitted can be refreshed by calling the component's paint method.
        Specified by:
        copyArea in class java.awt.Graphics
        Parameters:
        x - the x coordinate of the source rectangle.
        y - the y coordinate of the source rectangle.
        width - the width of the source rectangle.
        height - the height of the source rectangle.
        dx - the horizontal distance to copy the pixels.
        dy - the vertical distance to copy the pixels.
      • drawImage

        public boolean drawImage​(java.awt.Image img,
                                 int x,
                                 int y,
                                 java.awt.image.ImageObserver observer)
        Draws as much of the specified image as is currently available. The image is drawn with its top-left corner at (xy) in this graphics context's coordinate space. Transparent pixels in the image do not affect whatever pixels are already there.

        This method returns immediately in all cases, even if the complete image has not yet been loaded, and it has not been dithered and converted for the current output device.

        If the image has not yet been completely loaded, then drawImage returns false. As more of the image becomes available, the process that draws the image notifies the specified image observer.

        Specified by:
        drawImage in class java.awt.Graphics
        Parameters:
        img - the specified image to be drawn.
        x - the x coordinate.
        y - the y coordinate.
        observer - object to be notified as more of the image is converted.
        See Also:
        Image, ImageObserver, ImageObserver.imageUpdate(java.awt.Image, int, int, int, int, int)
      • drawImage

        public boolean drawImage​(java.awt.Image img,
                                 int x,
                                 int y,
                                 int width,
                                 int height,
                                 java.awt.image.ImageObserver observer)
        Draws as much of the specified image as has already been scaled to fit inside the specified rectangle.

        The image is drawn inside the specified rectangle of this graphics context's coordinate space, and is scaled if necessary. Transparent pixels do not affect whatever pixels are already there.

        This method returns immediately in all cases, even if the entire image has not yet been scaled, dithered, and converted for the current output device. If the current output representation is not yet complete, then drawImage returns false. As more of the image becomes available, the process that draws the image notifies the image observer by calling its imageUpdate method.

        A scaled version of an image will not necessarily be available immediately just because an unscaled version of the image has been constructed for this output device. Each size of the image may be cached separately and generated from the original data in a separate image production sequence.

        Specified by:
        drawImage in class java.awt.Graphics
        Parameters:
        img - the specified image to be drawn.
        x - the x coordinate.
        y - the y coordinate.
        width - the width of the rectangle.
        height - the height of the rectangle.
        observer - object to be notified as more of the image is converted.
        See Also:
        Image, ImageObserver, ImageObserver.imageUpdate(java.awt.Image, int, int, int, int, int)
      • dispose

        public void dispose()
        Disposes of this graphics context and releases any system resources that it is using. A Graphics object cannot be used after disposehas been called.

        When a Java program runs, a large number of Graphics objects can be created within a short time frame. Although the finalization process of the garbage collector also disposes of the same system resources, it is preferable to manually free the associated resources by calling this method rather than to rely on a finalization process which may not run to completion for a long period of time.

        Graphics objects which are provided as arguments to the paint and update methods of components are automatically released by the system when those methods return. For efficiency, programmers should call dispose when finished using a Graphics object only if it was created directly from a component or another Graphics object.

        Specified by:
        dispose in class java.awt.Graphics
        See Also:
        Graphics.finalize(), Component.paint(java.awt.Graphics), Component.update(java.awt.Graphics), Component.getGraphics(), Graphics.create()
      • drawImage

        public boolean drawImage​(java.awt.Image img,
                                 java.awt.geom.AffineTransform xform,
                                 java.awt.image.ImageObserver obs)
        Renders an image, applying a transform from image space into user space before drawing. The transformation from user space into device space is done with the current Transform in the Graphics2D. The specified transformation is applied to the image before the transform attribute in the Graphics2D context is applied. The rendering attributes applied include the Clip, Transform, and Composite attributes. Note that no rendering is done if the specified transform is noninvertible.
        Overrides:
        drawImage in class AbstractGraphics2D
        Parameters:
        img - the Image to be rendered
        xform - the transformation from image space into user space
        obs - the ImageObserver to be notified as more of the Image is converted
        Returns:
        true if the Image is fully loaded and completely rendered; false if the Image is still being loaded.
        See Also:
        AbstractGraphics2D.setTransform(AffineTransform), AbstractGraphics2D.setComposite(java.awt.Composite), AbstractGraphics2D.setClip(Shape)
      • drawImage

        public void drawImage​(java.awt.image.BufferedImage img,
                              java.awt.image.BufferedImageOp op,
                              int x,
                              int y)
        Renders a BufferedImage that is filtered with a BufferedImageOp. The rendering attributes applied include the Clip, Transform and Composite attributes. This is equivalent to:
         img1 = op.filter(img, null);
         drawImage(img1, new AffineTransform(1f,0f,0f,1f,x,y), null);
         
        Overrides:
        drawImage in class AbstractGraphics2D
        Parameters:
        op - the filter to be applied to the image before rendering
        img - the BufferedImage to be rendered
        x - the x coordinate in user space where the upper left corner of the image is rendered
        y - the y coordinate in user space where the upper left corner of the image is rendered
        See Also:
        AbstractGraphics2D.setTransform(AffineTransform), AbstractGraphics2D.setComposite(java.awt.Composite), AbstractGraphics2D.setClip(Shape)
      • drawRenderedImage

        public void drawRenderedImage​(java.awt.image.RenderedImage img,
                                      java.awt.geom.AffineTransform trans2)
        Renders a RenderedImage, applying a transform from image space into user space before drawing. The transformation from user space into device space is done with the current Transform in the Graphics2D. The specified transformation is applied to the image before the transform attribute in the Graphics2D context is applied. The rendering attributes applied include the Clip, Transform, and Composite attributes. Note that no rendering is done if the specified transform is noninvertible.
        Specified by:
        drawRenderedImage in class java.awt.Graphics2D
        Parameters:
        img - the image to be rendered
        trans2 - the transformation from image space into user space
        See Also:
        AbstractGraphics2D.setTransform(AffineTransform), AbstractGraphics2D.setComposite(java.awt.Composite), AbstractGraphics2D.setClip(Shape)
      • drawRenderableImage

        public void drawRenderableImage​(java.awt.image.renderable.RenderableImage img,
                                        java.awt.geom.AffineTransform trans2)
        Renders a RenderableImage, applying a transform from image space into user space before drawing. The transformation from user space into device space is done with the current Transform in the Graphics2D. The specified transformation is applied to the image before the transform attribute in the Graphics2D context is applied. The rendering attributes applied include the Clip, Transform, and Composite attributes. Note that no rendering is done if the specified transform is noninvertible.

        Rendering hints set on the Graphics2D object might be used in rendering the RenderableImage. If explicit control is required over specific hints recognized by a specific RenderableImage, or if knowledge of which hints are used is required, then a RenderedImage should be obtained directly from the RenderableImage and rendered using drawRenderedImage(RenderedImage, AffineTransform).

        Specified by:
        drawRenderableImage in class java.awt.Graphics2D
        Parameters:
        img - the image to be rendered
        trans2 - the transformation from image space into user space
        See Also:
        AbstractGraphics2D.setTransform(AffineTransform), AbstractGraphics2D.setComposite(java.awt.Composite), AbstractGraphics2D.setClip(Shape), drawRenderedImage(java.awt.image.RenderedImage, java.awt.geom.AffineTransform)
      • drawString

        public void drawString​(java.lang.String s,
                               float x,
                               float y)
        Renders the text specified by the specified String, using the current Font and Paint attributes in the Graphics2D context. The baseline of the first character is at position (xy) in the User Space. The rendering attributes applied include the Clip, Transform, Paint, Font and Composite attributes. For characters in script systems such as Hebrew and Arabic, the glyphs can be rendered from right to left, in which case the coordinate supplied is the location of the leftmost character on the baseline.
        Specified by:
        drawString in class java.awt.Graphics2D
        Parameters:
        s - the String to be rendered
        x - the x coordinate where the String should be rendered
        y - the y coordinate where the String should be rendered
        See Also:
        AbstractGraphics2D.setPaint(Paint), Graphics.setColor(java.awt.Color), Graphics.setFont(java.awt.Font), AbstractGraphics2D.setTransform(AffineTransform), AbstractGraphics2D.setComposite(java.awt.Composite), AbstractGraphics2D.setClip(Shape)
      • transformText

        private java.awt.geom.AffineTransform transformText​(float x,
                                                            float y)
      • drawString

        public void drawString​(java.text.AttributedCharacterIterator ati,
                               float x,
                               float y)
        Renders the text of the specified iterator, using the Graphics2D context's current Paint. The iterator must specify a font for each character. The baseline of the first character is at position (xy) in the User Space. The rendering attributes applied include the Clip, Transform, Paint, and Composite attributes. For characters in script systems such as Hebrew and Arabic, the glyphs can be rendered from right to left, in which case the coordinate supplied is the location of the leftmost character on the baseline.
        Specified by:
        drawString in class java.awt.Graphics2D
        Parameters:
        ati - the iterator whose text is to be rendered
        x - the x coordinate where the iterator's text is to be rendered
        y - the y coordinate where the iterator's text is to be rendered
        See Also:
        AbstractGraphics2D.setPaint(Paint), Graphics.setColor(java.awt.Color), AbstractGraphics2D.setTransform(AffineTransform), AbstractGraphics2D.setComposite(java.awt.Composite), AbstractGraphics2D.setClip(Shape)
      • setTextFontAttributes

        private boolean setTextFontAttributes​(java.text.AttributedCharacterIterator ati,
                                              java.awt.Font baseFont)
        Set the Element Font and Size attributes, depending on the AttributedCharacterIterator attributes.
      • setTextElementFill

        private void setTextElementFill​(java.text.AttributedCharacterIterator ati)
        Set the Element attributes, depending on the AttributedCharacterIterator attributes. The following attributes are set :
        • underline
        • weight (bold or plain)
        • style (italic or normal)
        • justification (start, end, or middle)
      • setTextElementAttributes

        private void setTextElementAttributes​(SVGGraphicContext tspanGC,
                                              java.text.AttributedCharacterIterator ati)
      • isBold

        private boolean isBold​(java.text.AttributedCharacterIterator ati)
        Return true if the AttributedCharacterIterator is bold (at its current position).
      • isItalic

        private boolean isItalic​(java.text.AttributedCharacterIterator ati)
        Return true if the AttributedCharacterIterator is italic (at its current position).
      • isUnderline

        private boolean isUnderline​(java.text.AttributedCharacterIterator ati)
        Return true if the AttributedCharacterIterator is underlined (at its current position).
      • isStrikeThrough

        private boolean isStrikeThrough​(java.text.AttributedCharacterIterator ati)
        Return true if the AttributedCharacterIterator is striked through (at its current position).
      • getDeviceConfiguration

        public java.awt.GraphicsConfiguration getDeviceConfiguration()
        Returns the device configuration associated with this Graphics2D.
        Specified by:
        getDeviceConfiguration in class java.awt.Graphics2D
      • setUnsupportedAttributes

        public void setUnsupportedAttributes​(java.util.Set attrs)
        This method let's users indicate that they don't care that certain text attributes will not be properly converted to SVG, in exchange when those attributes are used they will get real SVG text instead of paths.
        Parameters:
        attrs - The set of attrs to treat as unsupported, and if present cause text to be drawn as paths. If null ACI text will be rendered as text (unless 'textAsShapes' is set).
      • usesUnsupportedAttributes

        public boolean usesUnsupportedAttributes​(java.text.AttributedCharacterIterator aci)