org.w3c.dom.svg.SVGDocument Java Examples

The following examples show how to use org.w3c.dom.svg.SVGDocument. 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: InteractiveMapRenderer.java    From Knowage-Server with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * Adds the href elements and click events
 *
 * @param targetMap
 *            the target svg
 * @param featureElement
 *            the svg element to manage
 * @param elementId
 *            the svg element id
 * @param drillId
 *            the drill id
 * @param linkUrl
 *            the link url
 * @param linkType
 *            the link type ('cross' or 'drill')
 *
 */
private void addHRefLinksCross(SVGDocument targetMap, Element featureElement, JSONArray JSONValues, JSONArray JSONCross,
		IDataMartProvider datamatProvider) {
	logger.debug("IN");
	Element linkCrossElement = targetMap.createElement("a");
	linkCrossElement.setAttribute("xlink:href", "javascript:void(0)");

	if (featureElement.hasAttribute("style")) {
		String elementStyle = featureElement.getAttribute("style");
		elementStyle = elementStyle + ";cursor:pointer";
		featureElement.setAttribute("style", elementStyle);
	} else {
		featureElement.setAttribute("style", "cursor:pointer");
	}

	featureElement.setAttribute("onclick", "javascript:clickedElementCrossNavigation('" + JSONValues.toString() + "', '" + JSONCross.toString() + "')");

	logger.debug("OUT");
}
 
Example #2
Source File: WrappingSvgDataToGraphics2DRenderer.java    From jasperreports with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Override
protected SVGDocument getSvgDocument(
	JasperReportsContext jasperReportsContext,
	SVGDocumentFactory documentFactory
	) throws JRException
{
	try
	{
		return 
			documentFactory.createSVGDocument(
				null, 
				new ByteArrayInputStream(
					dataRenderer.getData(jasperReportsContext)
					)
				);
	}
	catch (IOException e)
	{
		throw new JRRuntimeException(e);
	}
}
 
Example #3
Source File: SVGMapMerger.java    From Knowage-Server with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * Merge map.
 *
 * @param srcMap
 *            the src map
 * @param dstMap
 *            the dst map
 * @param srcId
 *            the src id
 * @param dstId
 *            the dst id
 */
public static void mergeMap(SVGDocument srcMap, SVGDocument dstMap, String srcId, String dstId) {
	SVGElement srcMapRoot;
	Element srcElement;
	Element dstElement;

	srcMapRoot = srcMap.getRootElement();
	srcElement = (srcId == null ? srcMapRoot : srcMap.getElementById(srcId));

	dstElement = dstMap.getElementById(dstId);

	NodeList nodeList = srcElement.getChildNodes();
	for (int i = 0; i < nodeList.getLength(); i++) {
		Node node = nodeList.item(i);
		Node importedNode = dstMap.importNode(node, true);
		dstElement.appendChild(importedNode);
	}
}
 
Example #4
Source File: SvgDataSniffer.java    From jasperreports with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * 
 */
public SvgInfo getSvgInfo(byte[] data)
{
	try
	{
		SVGDocument document = 
			documentFactory.createSVGDocument(
				null,
				new ByteArrayInputStream(data)
				);
		
		return new SvgInfo(document.getInputEncoding());
	}
	catch (IOException e)
	{
		return null;
	}
}
 
Example #5
Source File: InteractiveMapRenderer.java    From Knowage-Server with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * Import scripts.
 *
 * @param doc
 *            the doc
 */
private void importScripts(SVGDocument doc) {
	importScipt(doc, "helper_functions.js");
	importScipt(doc, "timer.js");
	importScipt(doc, "mapApp.js");
	importScipt(doc, "timer.js");
	importScipt(doc, "slider.js");
	importScipt(doc, "button.js");
	importScipt(doc, "Window.js");
	importScipt(doc, "checkbox_and_radiobutton.js");
	importScipt(doc, "navigation.js");
	importScipt(doc, "tabgroup.js");
	importScipt(doc, "colourPicker.js");

	importScipt(doc, "custom/Utils.js");
	importScipt(doc, "custom/BarChart.js");
	importScipt(doc, "custom/NavigationWindow.js");
	importScipt(doc, "custom/LayersWindow.js");
	importScipt(doc, "custom/ThematicWindow.js");
	importScipt(doc, "custom/DetailsWindow.js");
	importScipt(doc, "custom/LegendWindow.js");
	importScipt(doc, "custom/ColourPickerWindow.js");
	importScipt(doc, "custom/ThresholdsFactory.js");
	importScipt(doc, "custom/ColourRangesFactory.js");

}
 
Example #6
Source File: Export.java    From PDV with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Export component to pdf format
 * @param component Component
 * @param bounds Rectangle
 * @param exportFile Export file
 * @throws IOException
 * @throws TranscoderException
 */
private static void exportSVG(Component component, Rectangle bounds, File exportFile) throws IOException, TranscoderException {

    DOMImplementation domImplementation = SVGDOMImplementation.getDOMImplementation();
    String svgNS = "http://www.w3.org/2000/svg";
    SVGDocument svgDocument = (SVGDocument) domImplementation.createDocument(svgNS, "svg", null);

    SVGGraphics2D svgGraphics2D = new SVGGraphics2D(svgDocument);
    svgGraphics2D.setSVGCanvasSize(bounds.getSize());

    component.paintAll(svgGraphics2D);

    if (new File(exportFile.getAbsolutePath() + ".temp").exists()) {
        new File(exportFile.getAbsolutePath() + ".temp").delete();
    }

    OutputStream outputStream = new FileOutputStream(exportFile);
    BufferedOutputStream bos = new BufferedOutputStream(outputStream);
    Writer out = new OutputStreamWriter(bos, "UTF-8");

    svgGraphics2D.stream(out, true);
    outputStream.flush();
    outputStream.close();
    out.close();
    bos.close();
}
 
Example #7
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 #8
Source File: Export.java    From PDV with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Constructor
 * @param chart JFreeChart to export
 * @param bounds Dimensions of the viewport
 * @param exportFile Output file
 * @param imageType Image type
 */
public static void exportPic(JFreeChart chart, Rectangle bounds, File exportFile, ImageType imageType)
        throws IOException, TranscoderException {

    DOMImplementation domImplementation = SVGDOMImplementation.getDOMImplementation();
    String svgNS = "http://www.w3.org/2000/svg";
    SVGDocument svgDocument = (SVGDocument) domImplementation.createDocument(svgNS, "svg", null);

    SVGGraphics2D svgGraphics2D = new SVGGraphics2D(svgDocument);
    svgGraphics2D.setSVGCanvasSize(bounds.getSize());

    chart.draw(svgGraphics2D, bounds);

    exportExceptedFormatPic(exportFile, imageType, svgGraphics2D);
}
 
Example #9
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 #10
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 #11
Source File: InteractiveMapRenderer.java    From Knowage-Server with GNU Affero General Public License v3.0 5 votes vote down vote up
private void addHRefLinksDrill(SVGDocument targetMap, Element featureElement, String elementId, String drillId, String linkUrl) {
	logger.debug("IN");
	Element linkCrossElement = targetMap.createElement("a");
	linkCrossElement.setAttribute("xlink:href", linkUrl);

	if (featureElement.hasAttribute("style")) {
		String elementStyle = featureElement.getAttribute("style");
		elementStyle = elementStyle + ";cursor:pointer";
		featureElement.setAttribute("style", elementStyle);
	} else {
		featureElement.setAttribute("style", "cursor:pointer");
	}

	// get document_id
	String documentId = (String) this.getEnv().get("DOCUMENT_ID");

	JSONObject jsonOEnv = new JSONObject();
	String strEnv = "";
	try {
		jsonOEnv = JSONUtils.getJsonFromMap(this.getEnv());
		jsonOEnv.remove("ENV_USER_PROFILE"); // clean profile info for correct url
		jsonOEnv.remove("level");
		jsonOEnv.remove("DOCUMENT_OUTPUT_PARAMETERS");
		strEnv = "&" + JSONUtils.getQueryString(jsonOEnv);
		// strEnv = SpagoBIUtilities.encode(strEnv.substring(0, strEnv.length() - 1)); //2017-29-30 commented because changes the parameter values
	} catch (JSONException je) {
		logger.error("An error occured while convert map [env] to json object: " + je);
	}
	// String strEnv = StringUtils.mapToString(this.getEnv());

	if (drillId == null) {
		// featureElement.setAttribute("onclick", "javascript:clickedElement('" + documentId + "','" + elementId + "')");
		featureElement.setAttribute("onclick", "javascript:clickedElement('" + strEnv + "','" + documentId + "','" + elementId + "')");
	} else {
		// featureElement.setAttribute("onclick", "javascript:clickedElement('" + documentId + "','" + elementId + "','" + drillId + "')");
		featureElement.setAttribute("onclick", "javascript:clickedElement('" + strEnv + "','" + documentId + "','" + elementId + "','" + drillId + "')");
	}

	logger.debug("OUT");
}
 
Example #12
Source File: InteractiveMapRenderer.java    From Knowage-Server with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * Include scripts.
 *
 * @param doc
 *            the doc
 */
private void includeScripts(SVGDocument doc) {
	Element scriptInit = doc.getElementById("included_scripts");
	Node scriptText = scriptInit.getFirstChild();
	StringBuffer buffer = new StringBuffer();
	includeScript(buffer, "helper_functions.js");
	includeScript(buffer, "timer.js");
	includeScript(buffer, "mapApp.js");
	includeScript(buffer, "timer.js");
	includeScript(buffer, "slider.js");
	includeScript(buffer, "button.js");
	includeScript(buffer, "Window.js");
	includeScript(buffer, "checkbox_and_radiobutton.js");
	includeScript(buffer, "navigation.js");
	includeScript(buffer, "tabgroup.js");
	includeScript(buffer, "colourPicker.js");

	includeScript(buffer, "custom/Utils.js");
	includeScript(buffer, "custom/BarChart.js");
	includeScript(buffer, "custom/NavigationWindow.js");
	includeScript(buffer, "custom/LayersWindow.js");
	includeScript(buffer, "custom/ThematicWindow.js");
	includeScript(buffer, "custom/DetailsWindow.js");
	includeScript(buffer, "custom/LegendWindow.js");
	includeScript(buffer, "custom/ColourPickerWindow.js");
	includeScript(buffer, "custom/ThresholdsFactory.js");
	includeScript(buffer, "custom/ColourRangesFactory.js");

	scriptText.setNodeValue(buffer.toString());
}
 
Example #13
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 #14
Source File: InteractiveMapRenderer.java    From Knowage-Server with GNU Affero General Public License v3.0 5 votes vote down vote up
private void importScipt(SVGDocument map, String scriptName) {
	Element script = map.createElement("script");
	script.setAttribute("type", "text/ecmascript");
	script.setAttribute("xlink:href", (String) getEnv().get(SvgViewerEngineConstants.ENV_CONTEXT_URL) + "/js/lib/svg-widgets/" + scriptName);
	Element importsBlock = map.getElementById("imported_scripts");
	importsBlock.appendChild(script);
	Node lf = map.createTextNode("\n");
	importsBlock.appendChild(lf);
}
 
Example #15
Source File: InteractiveMapRenderer.java    From Knowage-Server with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * Sets the main map bkg rect dimension.
 *
 * @param masterMap
 *            the master map
 * @param targetMap
 *            the target map
 */
public void setMainMapBkgRectDimension(SVGDocument masterMap, SVGDocument targetMap) {
	String viewBox = targetMap.getRootElement().getAttribute("viewBox");
	String[] chunks = viewBox.split(" ");
	String x = chunks[0];
	String y = chunks[1];
	String width = chunks[2];
	String height = chunks[3];
	Element mapBackgroundRect = masterMap.getElementById("mapBackgroundRect");
	mapBackgroundRect.setAttribute("x", x);
	mapBackgroundRect.setAttribute("y", y);
	mapBackgroundRect.setAttribute("width", width);
	mapBackgroundRect.setAttribute("height", height);
}
 
Example #16
Source File: SvgCache.java    From hop with Apache License 2.0 5 votes vote down vote up
public synchronized static SvgCacheEntry loadSvg( SvgFile svgFile ) throws HopException {

    SvgCacheEntry cacheEntry = findSvg( svgFile.getFilename() );
    if (cacheEntry!=null) {
      return cacheEntry;
    }

    try {
      String parser = XMLResourceDescriptor.getXMLParserClassName();
      SAXSVGDocumentFactory factory = new SAXSVGDocumentFactory( parser );
      InputStream svgStream = svgFile.getClassLoader().getResourceAsStream( svgFile.getFilename() );

      if ( svgStream == null ) {
        throw new HopException( "Unable to find file '" + svgFile.getFilename() + "'" );
      }
      SVGDocument svgDocument = factory.createSVGDocument( svgFile.getFilename(), svgStream );

      Element elSVG = svgDocument.getRootElement();
      String widthString = elSVG.getAttribute( "width" );
      String heightString = elSVG.getAttribute( "height" );
      double width = Const.toDouble( widthString.replace( "px", "" ), -1 );
      double height = Const.toDouble( heightString.replace( "px", "" ), -1 );
      if ( width < 0 || height < 0 ) {
        throw new HopException( "Unable to find valid width or height in SVG document " + svgFile.getFilename() );
      }
      cacheEntry = new SvgCacheEntry( svgFile.getFilename(), svgDocument, (int)Math.round(width), (int)Math.round(height) );
      getInstance().fileDocumentMap.put( svgFile.getFilename(), cacheEntry );
      return cacheEntry;
    } catch ( Exception e ) {
      throw new HopException( "Error loading SVG file " + svgFile.getFilename(), e );
    }
  }
 
Example #17
Source File: SVGMapLoader.java    From Knowage-Server with GNU Affero General Public License v3.0 5 votes vote down vote up
public SVGDocument loadMapAsDocument(Content map) throws IOException {
	String mapContent;

	mapContent = new String(DECODER.decodeBuffer(map.getContent()));
	documentFactory = new SAXSVGDocumentFactory(parser);
	return (SVGDocument) documentFactory.createDocument(null, new StringReader(mapContent));
}
 
Example #18
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 #19
Source File: AbstractMapProvider.java    From Knowage-Server with GNU Affero General Public License v3.0 4 votes vote down vote up
@Override
public SVGDocument getSVGMapDOMDocument(HierarchyMember member) throws SvgViewerEngineRuntimeException {
	return getSVGMapDOMDocument(member);
}
 
Example #20
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 #21
Source File: QualifiedSVGResourceFactory.java    From androidsvgdrawable-plugin with Apache License 2.0 4 votes vote down vote up
private SVGDocument getSVGDocument(QualifiedSVGResource svg) throws IOException {
    String parser = XMLResourceDescriptor.getXMLParserClassName();
    SAXSVGDocumentFactory f = new SAXSVGDocumentFactory(parser);
    return (SVGDocument) f.createDocument(svg.toURI().toURL().toString());
}
 
Example #22
Source File: AbstractSvgDataToGraphics2DRenderer.java    From jasperreports with GNU Lesser General Public License v3.0 4 votes vote down vote up
/**
 * 
 */
protected abstract SVGDocument getSvgDocument(
	JasperReportsContext jasperReportsContext,
	SVGDocumentFactory documentFactory
	) throws JRException;
 
Example #23
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 #24
Source File: SvgCacheEntry.java    From hop with Apache License 2.0 4 votes vote down vote up
public SvgCacheEntry( String filename, SVGDocument svgDocument, int width, int height ) {
  this.filename = filename;
  this.svgDocument = svgDocument;
  this.width = width;
  this.height = height;
}
 
Example #25
Source File: AbstractMapProvider.java    From Knowage-Server with GNU Affero General Public License v3.0 4 votes vote down vote up
@Override
public SVGDocument getSVGMapDOMDocument(String mapName) throws SvgViewerEngineRuntimeException {
	return null;
}
 
Example #26
Source File: AbstractMapProvider.java    From Knowage-Server with GNU Affero General Public License v3.0 4 votes vote down vote up
@Override
public SVGDocument getSVGMapDOMDocument() throws SvgViewerEngineRuntimeException {
	return getSVGMapDOMDocument(selectedMapName);
}
 
Example #27
Source File: InteractiveMapRenderer.java    From Knowage-Server with GNU Affero General Public License v3.0 4 votes vote down vote up
/**
 * Show or hide elements through the specific column value
 *
 * @param masterMap
 *            the svg content
 *
 * @param geoIdField
 *            the element id field
 * @param visibilityIdField
 *            the visibility field
 */
private void showElements(SVGDocument masterMap, IField geoIdField, IField visibilityIdField) {
	logger.debug("IN");

	String id_element = (String) geoIdField.getValue();
	String elementVisibility = (String) visibilityIdField.getValue();
	try {
		Element element = masterMap.getElementById(id_element);
		if (element != null) {
			String displayStyle = "";
			String elementStyle = element.getAttribute("style");
			// clean style from ;;
			if (elementStyle.indexOf(";;") >= 0) {
				elementStyle = elementStyle.replaceAll(";;", ";");
			}
			// get original display option if present
			int displayStyleStart = elementStyle.indexOf("display:");
			String displayStyleValue = "";

			// if (displayStyleStart >= 0) {
			// int displayStyleEnd = -1;
			// try {
			// displayStyleEnd = elementStyle.indexOf(";", displayStyleStart);
			// displayStyleValue = elementStyle.substring(displayStyleStart, displayStyleEnd + 1);
			// } catch (StringIndexOutOfBoundsException se) {
			// logger.error("An error occured while getting style content of element with id [" + id_element
			// + "]. Please, check that ALL the style elements into the SVG have the final [;] char. Ex: [display:none;]");
			// throw se;
			// }
			// elementStyle = elementStyle.replace(displayStyleValue, ""); // clean old style
			// }

			// Manage 'display:none' or 'display:none;' properties
			if (displayStyleStart >= 0) {
				int displayStyleEnd = -1;
				String displayContent = "";
				try {
					// case with ; or other properties
					if (elementStyle.length() >= displayStyleStart + 13) {
						displayContent = elementStyle.substring(displayStyleStart, displayStyleStart + 13);
					} else {
						// case without ';'. Style value is : style="display:none"
						displayContent = elementStyle.substring(displayStyleStart, displayStyleStart + 12);
					}
					displayContent = displayContent.trim();
					if (displayContent.indexOf("none") >= 0) {
						displayStyleEnd = displayStyleStart + 12;
						if (displayContent.indexOf(";") > 0)
							displayStyleEnd = displayStyleEnd + 1;
					}
					displayStyleValue = elementStyle.substring(displayStyleStart, displayStyleEnd);
				} catch (StringIndexOutOfBoundsException se) {
					logger.error("An error occured while getting style content of element with id [" + id_element
							+ "]. Please, check that ALL the style elements into the SVG have the final [;] char. Ex: [display:none;]");
					throw se;
				}
				elementStyle = elementStyle.replace(displayStyleValue, ""); // clean old style
			}

			if (elementVisibility.equalsIgnoreCase("false")) {
				displayStyle = elementStyle + ";display:none;";
			} else {
				displayStyle = elementStyle;
			}
			// sets new visibility style for the element
			element.setAttribute("style", displayStyle);
		}
	} catch (Exception e) {
		logger.error("An error occured while managing show property for the element [" + id_element + "]");
		throw e;
	}
	logger.debug("OUT");
}
 
Example #28
Source File: InteractiveMapRenderer.java    From Knowage-Server with GNU Affero General Public License v3.0 4 votes vote down vote up
/**
 * Add label to the centroide
 *
 * @param masterMap
 *            the svg content
 * @param centroide
 *            the centroide svg element
 * @param labelGroup
 *            the svg label group element
 * @param aRecord
 *            the record with values
 * @param labelField
 *            the label field
 */
private void addLabels(SVGDocument masterMap, Element centroide, Element labelGroup, IRecord aRecord, IField labelField) {
	logger.debug("IN");
	labelGroup.setAttribute("transform", "translate(" + centroide.getAttribute("cx") + "," + centroide.getAttribute("cy") + ") scale(1)");
	labelGroup.setAttribute("display", "inherit");

	Element label = masterMap.createElement("text");
	label.setAttribute("x", "0");
	label.setAttribute("y", "0");

	label.setAttribute("font-family", "Arial,Helvetica");
	label.setAttribute("font-size", "12px");
	label.setAttribute("font-style", "normal");
	label.setAttribute("fill", "black");
	// label.setAttribute("text-anchor", "middle");
	// get text-anchor property:
	// 1. throught text-anchor property
	// 2. throught style property
	// 3. if it isn't found force 'middle' as default
	String anchor = "middle";
	String anchorProperty = centroide.getAttribute("text-anchor");
	if (anchorProperty != null && anchorProperty.equals("start") || anchorProperty.equals("middle") || anchorProperty.equals("end")) {
		anchor = anchorProperty;
	} else {
		String styleProperty = centroide.getAttribute("style");
		int anchorPropertyPosStart = styleProperty.indexOf("text-anchor:");
		int anchorPropertyPosEnd = styleProperty.indexOf(";", anchorPropertyPosStart);
		if (null != styleProperty && anchorPropertyPosStart >= 0) {
			anchorProperty = styleProperty.substring(anchorPropertyPosStart + 12, anchorPropertyPosEnd);
			anchor = anchorProperty;
			// clean the style from the anchor information
			styleProperty = styleProperty.replace(styleProperty.substring(anchorPropertyPosStart, anchorPropertyPosEnd + 1), "");
			centroide.setAttribute("style", styleProperty);
		}
	}
	label.setAttribute("text-anchor", anchor);
	Node labelText = masterMap.createTextNode((String) labelField.getValue());
	label.appendChild(labelText);
	labelGroup.appendChild(label);
	if (labelGroup != null) {
		// append labels to default layer "valori"
		Element valuesLayer = masterMap.getElementById("_labels_layer");
		valuesLayer.appendChild(labelGroup);
	}

}
 
Example #29
Source File: Export.java    From PDV with GNU General Public License v3.0 4 votes vote down vote up
/**
 * Export component to pdf format
 * @param component Component
 * @param bounds Rectangle
 * @param exportFile Export file
 * @throws IOException
 * @throws TranscoderException
 */
private static void exportPDF(Component component, Rectangle bounds, File exportFile) throws IOException, TranscoderException {

    DOMImplementation domImplementation = SVGDOMImplementation.getDOMImplementation();
    String svgNS = "http://www.w3.org/2000/svg";
    SVGDocument svgDocument = (SVGDocument) domImplementation.createDocument(svgNS, "svg", null);

    SVGGraphics2D svgGraphics2D = new SVGGraphics2D(svgDocument);
    svgGraphics2D.setSVGCanvasSize(bounds.getSize());

    component.paintAll(svgGraphics2D);

    if (new File(exportFile.getAbsolutePath() + ".temp").exists()) {
        new File(exportFile.getAbsolutePath() + ".temp").delete();
    }

    File svgFile = new File(exportFile.getAbsolutePath() + ".temp");

    OutputStream outputStream = new FileOutputStream(svgFile);
    BufferedOutputStream bos = new BufferedOutputStream(outputStream);
    Writer out = new OutputStreamWriter(bos, "UTF-8");

    svgGraphics2D.stream(out, true);
    outputStream.flush();
    outputStream.close();
    out.close();
    bos.close();

    String svgURI = svgFile.toURI().toString();
    TranscoderInput svgInputFile = new TranscoderInput(svgURI);

    OutputStream outstream = new FileOutputStream(exportFile);
    bos = new BufferedOutputStream(outstream);
    TranscoderOutput output = new TranscoderOutput(bos);

    Transcoder pdfTranscoder = new PDFTranscoder();
    pdfTranscoder.addTranscodingHint(PDFTranscoder.KEY_DEVICE_RESOLUTION, (float) Toolkit.getDefaultToolkit().getScreenResolution());
    pdfTranscoder.transcode(svgInputFile, output);

    outstream.flush();
    outstream.close();
    bos.close();

    if (svgFile.exists()) {
        svgFile.delete();
    }

}
 
Example #30
Source File: SvgCache.java    From hop with Apache License 2.0 4 votes vote down vote up
public synchronized static void addSvg( String filename, SVGDocument svgDocument, int width, int height ) {
  getInstance().fileDocumentMap.put( filename, new SvgCacheEntry( filename, svgDocument, width, height ) );
}