org.apache.batik.bridge.BridgeContext Java Examples

The following examples show how to use org.apache.batik.bridge.BridgeContext. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: SVGFigure.java    From bonita-studio with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Reads color value from the document.
 */
protected Color getColor(final Element element, final String attributeName) {
    if (getDocument() == null || getDocument() != element.getOwnerDocument()) {
        return null;
    }
    Color color = null;
    // Make sure that CSSEngine is available.
    final BridgeContext ctx = transcoder.initCSSEngine();
    try {
        color = SVGUtils.toSWTColor(element, attributeName);
    } finally {
        if (ctx != null) {
            ctx.dispose();
        }
    }
    return color;
}
 
Example #2
Source File: SimpleImageTranscoder.java    From bonita-studio with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Call before querying for CSS properties. If document has CSS engine installed returns null. Client is responsible to
 * dispose bridge context if it was returned by this method.
 */
public BridgeContext initCSSEngine() {
	if (document == null) {
		return null;
	}
	final SVGOMDocument sd = (SVGOMDocument) document;
	if (sd.getCSSEngine() != null) {
		return null;
	}
	class BridgeContextEx extends BridgeContext {

		public BridgeContextEx() {
			super(SimpleImageTranscoder.this.userAgent);
			BridgeContextEx.this.setDocument(SimpleImageTranscoder.this.document);
			BridgeContextEx.this.initializeDocument(SimpleImageTranscoder.this.document);
		}
	}
	return new BridgeContextEx();
}
 
Example #3
Source File: SvgLayerFactory.java    From geomajas-project-server with GNU Affero General Public License v3.0 6 votes vote down vote up
private GraphicsNode createNode(String svgContent) throws GeomajasException {
	// batik magic
	String parser = XMLResourceDescriptor.getXMLParserClassName();
	SAXSVGDocumentFactory f = new SAXSVGDocumentFactory(parser);
	SVGDocument document;
	try {
		document = f.createSVGDocument("", new StringReader(svgContent));
	} catch (IOException e) {
		throw new RasterException(e, RasterException.BAD_SVG, "Cannot parse SVG");
	}
	UserAgent userAgent = new UserAgentAdapter();
	DocumentLoader loader = new DocumentLoader(userAgent);
	BridgeContext bridgeContext = new BridgeContext(userAgent, loader);
	bridgeContext.setDynamic(true);
	GVTBuilder builder = new GVTBuilder();
	return builder.build(bridgeContext, document);
}
 
Example #4
Source File: BaseScope.java    From pentaho-reporting with GNU Lesser General Public License v2.1 6 votes vote down vote up
public static Object _loadSvg( final Context cx, final Scriptable thisObj,
                               final Object[] args, final Function funObj ) {

  final String file = args[ 0 ].toString();
  try {
    final BaseScope scope = (BaseScope) thisObj;
    final String parser = "org.apache.xerces.parsers.SAXParser"; //XMLResourceDescriptor.getXMLParserClassName();
    final SAXSVGDocumentFactory f = new SAXSVGDocumentFactory( parser );
    final String uri = "file:" + scope.basePath + "/" + file;
    final SVGOMDocument doc = (SVGOMDocument) f.createDocument( uri );

    // Initialize the CSS Engine for the document
    final SVGDOMImplementation impl = (SVGDOMImplementation) SVGDOMImplementation.getDOMImplementation();
    final UserAgent userAgent = new UserAgentAdapter();
    final BridgeContext ctx = new BridgeContext( userAgent, new DocumentLoader( userAgent ) );
    doc.setCSSEngine( impl.createCSSEngine( doc, ctx ) );

    return Context.javaToJS( doc, scope );
  } catch ( Exception e ) {
    e.printStackTrace();
    logger.error( e );
    return Context.getUndefinedValue();
  }
}
 
Example #5
Source File: SwingUniversalImageSvg.java    From hop with Apache License 2.0 5 votes vote down vote up
public SwingUniversalImageSvg( SvgImage svg ) {
  this.svg = svg;

  // get GraphicsNode and size from svg document
  UserAgentAdapter userAgentAdapter = new UserAgentAdapter();
  DocumentLoader documentLoader = new DocumentLoader( userAgentAdapter );
  BridgeContext ctx = new BridgeContext( userAgentAdapter, documentLoader );
  GVTBuilder builder = new GVTBuilder();
  svgGraphicsNode = builder.build( ctx, svg.getDocument() );
  svgGraphicsSize = ctx.getDocumentSize();
}
 
Example #6
Source File: ViewContainerComponent.java    From jetpad-projectional-open-source with Apache License 2.0 5 votes vote down vote up
private void createGraphicsNode(SvgView view) {
  myBridgeContext = new BridgeContext(myUserAgent);
  myBridgeContext.setDynamic(true);

  myMapper = new SvgRootDocumentMapper(view.root().get());
  myMapper.attachRoot();

  GVTBuilder builder = new GVTBuilder();
  myGraphicsNode = builder.build(myBridgeContext, myMapper.getTarget());

  myUserAgent.getEventDispatcher().setRootNode(myGraphicsNode);
}
 
Example #7
Source File: SwingUniversalImageSvg.java    From pentaho-kettle with Apache License 2.0 5 votes vote down vote up
public SwingUniversalImageSvg( SvgImage svg ) {
  // get GraphicsNode and size from svg document
  UserAgentAdapter userAgentAdapter = new UserAgentAdapter();
  DocumentLoader documentLoader = new DocumentLoader( userAgentAdapter );
  BridgeContext ctx = new BridgeContext( userAgentAdapter, documentLoader );
  GVTBuilder builder = new GVTBuilder();
  svgGraphicsNode = builder.build( ctx, svg.getDocument() );
  svgGraphicsSize = ctx.getDocumentSize();
}
 
Example #8
Source File: SwtUniversalImageSvg.java    From pentaho-kettle with Apache License 2.0 5 votes vote down vote up
public SwtUniversalImageSvg( SvgImage svg ) {
  // get GraphicsNode and size from svg document
  UserAgentAdapter userAgentAdapter = new UserAgentAdapter();
  DocumentLoader documentLoader = new DocumentLoader( userAgentAdapter );
  BridgeContext ctx = new BridgeContext( userAgentAdapter, documentLoader );
  GVTBuilder builder = new GVTBuilder();
  svgGraphicsNode = builder.build( ctx, svg.getDocument() );
  svgGraphicsSize = ctx.getDocumentSize();
}
 
Example #9
Source File: QualifiedSVGResourceFactory.java    From androidsvgdrawable-plugin with Apache License 2.0 5 votes vote down vote up
private GraphicsNode getGraphicsNode(SVGDocument svgDocument, int dpi) throws IOException {
    UserAgent userAgent = new DensityAwareUserAgent(dpi);
    DocumentLoader loader = new DocumentLoader(userAgent);
    BridgeContext ctx = new BridgeContext(userAgent, loader);
    ctx.setDynamicState(BridgeContext.DYNAMIC);
    GVTBuilder builder = new GVTBuilder();
    GraphicsNode rootGN = builder.build(ctx, svgDocument);
    return rootGN;
}
 
Example #10
Source File: QualifiedSVGResourceFactory.java    From androidsvgdrawable-plugin with Apache License 2.0 5 votes vote down vote up
/**
 * Extract the viewbox of the input SVG
 * @return
 * @throws MalformedURLException
 * @throws IOException
 */
private Rectangle extractSVGBounds(QualifiedSVGResource svg) throws IOException {
    // check <svg> attributes first : x, y, width, height
    SVGDocument svgDocument = getSVGDocument(svg);
    SVGSVGElement svgElement = svgDocument.getRootElement();
    if (svgElement.getAttributeNode("width") != null && svgElement.getAttribute("height") != null) {

        UserAgent userAgent = new DensityAwareUserAgent(svg.getDensity().getDpi());
        UnitProcessor.Context context = org.apache.batik.bridge.UnitProcessor.createContext(
                new BridgeContext(userAgent), svgElement);

        float width = svgLengthInPixels(svgElement.getWidth().getBaseVal(), context);
        float height = svgLengthInPixels(svgElement.getHeight().getBaseVal(), context);
        float x = 0;
        float y = 0;
        // check x and y attributes
        if (svgElement.getX() != null && svgElement.getX().getBaseVal() != null) {
            x = svgLengthInPixels(svgElement.getX().getBaseVal(), context);
        }
        if (svgElement.getY() != null && svgElement.getY().getBaseVal() != null) {
            y = svgLengthInPixels(svgElement.getY().getBaseVal(), context);
        }

        return new Rectangle((int) floor(x), (int) floor(y), (int) ceil(width), (int) ceil(height));
    }

    // use computed bounds
    log.warn("Take time to fix desired width and height attributes of the root <svg> node for this file... " +
            "ROI will be computed by magic using Batik " + boundsType.name() + " bounds");
    return boundsType.getBounds(getGraphicsNode(svgDocument, svg.getDensity().getDpi()));
}
 
Example #11
Source File: PrimitiveDimensionProvider.java    From javafxsvg with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Override
public Dimension getDimension(Document document) {
	UserAgent agent = new UserAgentAdapter();
	DocumentLoader loader = new DocumentLoader(agent);

	BridgeContext context = new BridgeContext(agent, loader);
	context.setDynamic(true);

	GVTBuilder builder = new GVTBuilder();
	Rectangle2D primitiveBounds = builder.build(context, document).getPrimitiveBounds();
	return new Dimension((float)primitiveBounds.getWidth(), (float)primitiveBounds.getHeight());
}
 
Example #12
Source File: WappalyzerJsonParser.java    From zap-extensions with Apache License 2.0 5 votes vote down vote up
private static ImageIcon createSvgIcon(URL url) throws Exception {
    if (url == null) {
        return null;
    }
    String xmlParser = XMLResourceDescriptor.getXMLParserClassName();
    SAXSVGDocumentFactory df = new SAXSVGDocumentFactory(xmlParser);
    SVGDocument doc = null;
    GraphicsNode svgIcon = null;
    try {
        doc = df.createSVGDocument(url.toString());
    } catch (RuntimeException re) {
        // v1 SVGs are unsupported
        return null;
    }
    doc.getRootElement().setAttribute("width", String.valueOf(SIZE));
    doc.getRootElement().setAttribute("height", String.valueOf(SIZE));
    UserAgent userAgent = new UserAgentAdapter();
    DocumentLoader loader = new DocumentLoader(userAgent);
    GVTBuilder builder = new GVTBuilder();
    try {
        svgIcon = builder.build(new BridgeContext(userAgent, loader), doc);
    } catch (BridgeException | StringIndexOutOfBoundsException ex) {
        logger.debug("Failed to parse SVG. " + ex.getMessage());
        return null;
    }

    AffineTransform transform = new AffineTransform(1, 0.0, 0.0, 1, 0, 0);
    BufferedImage image = new BufferedImage(SIZE, SIZE, BufferedImage.TYPE_INT_ARGB);
    Graphics2D g2d = addRenderingHints(image);
    svgIcon.setTransform(transform);
    svgIcon.paint(g2d);
    g2d.dispose();
    return new ImageIcon(image);
}
 
Example #13
Source File: SVGLoader.java    From mars-sim with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Load the SVG image with the specified name. This operation may either
 * create a new graphics node of returned a previously created one.
 * @param name Name of the SVG file to load.
 * @return GraphicsNode containing SVG image or null if none found.
 */
public static GraphicsNode getSVGImage(String name) {
	if (svgCache == null) svgCache = new HashMap<String, GraphicsNode>();

	GraphicsNode found = svgCache.get(name);
	if (found == null) {
		String fileName = SVG_DIR + name;
		URL resource = SVGLoader.class.getResource(fileName);

		try {
			String xmlParser = XMLResourceDescriptor.getXMLParserClassName();
			SAXSVGDocumentFactory df = new SAXSVGDocumentFactory(xmlParser);
			SVGDocument doc = df.createSVGDocument(resource.toString());
			UserAgent userAgent = new UserAgentAdapter();
			DocumentLoader loader = new DocumentLoader(userAgent);
			BridgeContext ctx = new BridgeContext(userAgent, loader);
			ctx.setDynamicState(BridgeContext.DYNAMIC);
			GVTBuilder builder = new GVTBuilder();
			found = builder.build(ctx, doc);

			svgCache.put(name, found);
		}
		catch (Exception e) {
			System.err.println("getSVGImage error: " + fileName);
			e.printStackTrace(System.err);
		}
	}

	return found;
}
 
Example #14
Source File: SvgTranscoder.java    From radiance with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * Transcodes the SVG image into Java2D code. Does nothing if the
 * {@link #listener} is <code>null</code>.
 *
 * @param templateStream Stream with the template content
 */
public Document transcode(InputStream templateStream) {
    if (this.listener == null)
        return null;

    UserAgentAdapter ua = new UserAgentAdapter();
    DocumentLoader loader = new DocumentLoader(ua);

    BridgeContext batikBridgeContext = new BridgeContext(ua, loader);
    batikBridgeContext.setDynamicState(BridgeContext.DYNAMIC);
    ua.setBridgeContext(batikBridgeContext);

    GVTBuilder builder = new GVTBuilder();
    Document svgDoc;
    try {
        svgDoc = loader.loadDocument(this.uri);
        GraphicsNode gvtRoot = builder.build(batikBridgeContext, svgDoc);

        this.transcode(gvtRoot, templateStream);
        return svgDoc;
    } catch (IOException ex) {
        Logger.getLogger(SvgTranscoder.class.getName()).log(Level.SEVERE, null, ex);
        return null;
    } finally {
        try {
            loader.dispose();
            batikBridgeContext.dispose();
        } catch (Throwable t) {
            Logger.getLogger(SvgTranscoder.class.getName()).log(Level.SEVERE, null, t);
        }
    }
}
 
Example #15
Source File: SwtUniversalImageSvg.java    From hop with Apache License 2.0 5 votes vote down vote up
public SwtUniversalImageSvg( SvgImage svg ) {
  // get GraphicsNode and size from svg document
  UserAgentAdapter userAgentAdapter = new UserAgentAdapter();
  DocumentLoader documentLoader = new DocumentLoader( userAgentAdapter );
  BridgeContext ctx = new BridgeContext( userAgentAdapter, documentLoader );
  GVTBuilder builder = new GVTBuilder();
  svgGraphicsNode = builder.build( ctx, svg.getDocument() );
  svgGraphicsSize = ctx.getDocumentSize();
}
 
Example #16
Source File: BatikRenderer.java    From jasperreports with GNU Lesser General Public License v3.0 4 votes vote down vote up
protected synchronized void ensureSvg(JasperReportsContext jasperReportsContext) throws JRException
{
	if (rootNode != null)
	{
		// already loaded
		return;
	}

	ensureData(jasperReportsContext);
	
	try
	{
		UserAgent userAgent = new BatikUserAgent(jasperReportsContext);
		
		SVGDocumentFactory documentFactory =
			new SAXSVGDocumentFactory(userAgent.getXMLParserClassName(), true);
		documentFactory.setValidating(userAgent.isXMLParserValidating());

		SVGDocument document;
		if (svgText != null)
		{
			document = documentFactory.createSVGDocument(null,
					new StringReader(svgText));
		}
		else
		{
			document = documentFactory.createSVGDocument(null,
					new ByteArrayInputStream(svgData));
		}

		BridgeContext ctx = new BridgeContext(userAgent);
		ctx.setDynamic(true);
		GVTBuilder builder = new GVTBuilder();
		rootNode = builder.build(ctx, document);
		documentSize = ctx.getDocumentSize();
	}
	catch (IOException e)
	{
		throw new JRRuntimeException(e);
	}
}
 
Example #17
Source File: AbstractSvgDataToGraphics2DRenderer.java    From jasperreports with GNU Lesser General Public License v3.0 4 votes vote down vote up
protected synchronized GraphicsNode getRootNode(JasperReportsContext jasperReportsContext) throws JRException
{
	if (rootNodeRef == null || rootNodeRef.get() == null)
	{
		FontFamilyResolver fontFamilyResolver = BatikFontFamilyResolver.getInstance(jasperReportsContext);
		
		UserAgent userAgentForDoc = 
			new BatikUserAgent(
				fontFamilyResolver,
				BatikUserAgent.PIXEL_TO_MM_72_DPI
				);
		
		SVGDocumentFactory documentFactory =
			new SAXSVGDocumentFactory(userAgentForDoc.getXMLParserClassName(), true);
		documentFactory.setValidating(userAgentForDoc.isXMLParserValidating());

		SVGDocument document = getSvgDocument(jasperReportsContext, documentFactory);

		Node svgNode = document.getElementsByTagName("svg").item(0);
		Node svgWidthNode = svgNode.getAttributes().getNamedItem("width");
		Node svgHeightNode = svgNode.getAttributes().getNamedItem("height");
		String strSvgWidth = svgWidthNode == null ? null : svgWidthNode.getNodeValue().trim();
		String strSvgHeight = svgHeightNode == null ? null : svgHeightNode.getNodeValue().trim();
		
		float pixel2mm = BatikUserAgent.PIXEL_TO_MM_72_DPI;
		if (
			(strSvgWidth != null && strSvgWidth.endsWith("mm"))
			|| (strSvgHeight != null && strSvgHeight.endsWith("mm"))
			)
		{
			pixel2mm = BatikUserAgent.PIXEL_TO_MM_96_DPI;
		}
		
		UserAgent userAgentForCtx = 
			new BatikUserAgent(
				fontFamilyResolver,
				pixel2mm
				);
			
		BridgeContext ctx = new BridgeContext(userAgentForCtx);
		ctx.setDynamic(true);
		GVTBuilder builder = new GVTBuilder();
		GraphicsNode rootNode = builder.build(ctx, document);
		rootNodeRef = new SoftReference<GraphicsNode>(rootNode);
		
		//copying the document size object because it has a reference to SVGSVGElementBridge,
		//which prevents rootNodeRef from being cleared by the garbage collector
		Dimension2D svgSize = ctx.getDocumentSize();
		documentSize = new SimpleDimension2D(svgSize.getWidth(), svgSize.getHeight());
	}
	
	return rootNodeRef.get();
}
 
Example #18
Source File: GuiUtils.java    From workcraft with MIT License 4 votes vote down vote up
public static ImageIcon createIconFromSVG(String path, int height, int width, Color background) {
    try {
        System.setProperty("org.apache.batik.warn_destination", "false");
        Document document;

        String parser = XMLResourceDescriptor.getXMLParserClassName();
        SAXSVGDocumentFactory f = new SAXSVGDocumentFactory(parser);

        document = f.createDocument(ClassLoader.getSystemResource(path).toString());

        UserAgentAdapter userAgentAdapter = new UserAgentAdapter();
        BridgeContext bridgeContext = new BridgeContext(userAgentAdapter);
        GVTBuilder builder = new GVTBuilder();

        GraphicsNode graphicsNode = builder.build(bridgeContext, document);

        double sizeY = bridgeContext.getDocumentSize().getHeight();
        double sizeX = bridgeContext.getDocumentSize().getWidth();

        BufferedImage bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);

        Graphics2D g2d = (Graphics2D) bufferedImage.getGraphics();
        if (background != null) {
            g2d.setColor(background);
            g2d.fillRect(0, 0, width, height);
        }

        g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        g2d.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
        g2d.setRenderingHint(RenderingHints.KEY_FRACTIONALMETRICS, RenderingHints.VALUE_FRACTIONALMETRICS_ON);
        g2d.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
        g2d.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, RenderingHints.VALUE_STROKE_PURE);
        g2d.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);

        double scaleX = (width - 1) / sizeX;
        double scaleY = (height - 1) / sizeY;
        double scale = Math.min(scaleX, scaleY);
        g2d.scale(scale, scale);
        g2d.translate(0.5, 0.5);

        graphicsNode.paint(g2d);
        g2d.dispose();
        return new ImageIcon(bufferedImage);
    } catch (Throwable e) {
        System.err.println("Failed to load SVG file " + path);
        System.err.println(e);
        return null;
    }
}
 
Example #19
Source File: SVGIcon.java    From netbeans with Apache License 2.0 4 votes vote down vote up
/**
 * Load the original SVG resource.
 *
 * @param toSize if not null, will be set to the image's size
 */
private static GraphicsNode loadGraphicsNode(URL url, Dimension toSize)
        throws IOException
{
    Parameters.notNull("url", url);
    final GraphicsNode graphicsNode;
    final Dimension2D documentSize;
    final Document doc;
    InputStream is = url.openStream();
    try {
        // See http://batik.2283329.n4.nabble.com/rendering-directly-to-java-awt-Graphics2D-td3716202.html
        SAXSVGDocumentFactory factory = DOCUMENT_FACTORY.get();
        /* Don't provide an URI here; we shouldn't commit to supporting relative links from
        loaded SVG documents. */
        doc = factory.createDocument(null, is);
        UserAgent userAgent = new UserAgentAdapter();
        DocumentLoader loader = new DocumentLoader(userAgent);
        BridgeContext bctx = new BridgeContext(userAgent, loader);
        try {
            bctx.setDynamicState(BridgeContext.STATIC);
            graphicsNode = new GVTBuilder().build(bctx, doc);
            documentSize = bctx.getDocumentSize();
        } finally {
            bctx.dispose();
        }
    } catch (RuntimeException e) {
        /* Rethrow the many different exceptions that can occur when parsing invalid SVG files;
        DOMException, BridgeException etc. */
        throw new IOException("Error parsing SVG file", e);
    } finally {
        is.close();
    }
    if (toSize != null) {
        int width = (int) Math.ceil(documentSize.getWidth());
        int height = (int) Math.ceil(documentSize.getHeight());
        final int widthLimited = Math.min(MAX_DIMENSION_PIXELS, width);
        final int heightLimited = Math.min(MAX_DIMENSION_PIXELS, height);
        if (width != widthLimited || height != heightLimited) {
            LOG.log(Level.WARNING,
                    "SVG image {0} too large (dimensions were {1}x{2}, each side can be at most {3}px)",
                    new Object[]{url, width, height, MAX_DIMENSION_PIXELS});
        } else if (width <= 1 && height <= 1) {
            LOG.log(Level.WARNING,
                    "SVG image {0} did not specify a width/height, or is incorrectly sized", url);
        }
        toSize.width = widthLimited;
        toSize.height = heightLimited;
    }
    return graphicsNode;
}
 
Example #20
Source File: BatikLoader.java    From svg2vector with Apache License 2.0 2 votes vote down vote up
/**
 * Returns the loader's bridge context.
 * @return bridge context, null if no document loaded
 */
public BridgeContext getBridgeContext(){
	return this.bridgeContext;
}