org.apache.batik.dom.GenericDOMImplementation Java Examples

The following examples show how to use org.apache.batik.dom.GenericDOMImplementation. 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: SVGExporter.java    From MogwaiERDesignerNG with GNU General Public License v3.0 6 votes vote down vote up
@Override
public void exportToStream(Component aComponent, OutputStream aStream) throws IOException {
    DOMImplementation theDomImpl = GenericDOMImplementation.getDOMImplementation();
    Document theDocument = theDomImpl.createDocument(null, "svg", null);
    SVGGraphics2D theSvgGenerator = new SVGGraphics2D(theDocument);
    RepaintManager theRepaintManager = RepaintManager.currentManager(aComponent);
    theRepaintManager.setDoubleBufferingEnabled(false);

    Dimension theSize = aComponent.getPreferredSize();
    aComponent.setSize(theSize);

    aComponent.paint(theSvgGenerator);
    Writer theWriter = new OutputStreamWriter(aStream, PlatformConfig.getXMLEncoding());
    theSvgGenerator.stream(theWriter, false);
    theRepaintManager.setDoubleBufferingEnabled(true);

    theWriter.flush();
    theWriter.close();
}
 
Example #2
Source File: GetWorkflowImageServlet.java    From hop with Apache License 2.0 6 votes vote down vote up
private String generateWorkflowSvgImage( WorkflowMeta workflowMeta ) throws Exception {
  float magnification = ZOOM_FACTOR;
  Point maximum = workflowMeta.getMaximum();
  maximum.multiply( magnification );

  DOMImplementation domImplementation = GenericDOMImplementation.getDOMImplementation();

  // Create an instance of org.w3c.dom.Document.
  String svgNamespace = "http://www.w3.org/2000/svg";
  Document document = domImplementation.createDocument(svgNamespace, "svg", null);

  HopSvgGraphics2D graphics2D = new HopSvgGraphics2D( document );

  SvgGc gc = new SvgGc( graphics2D, new Point(maximum.x,maximum.y), 32, 0, 0 );
  WorkflowPainter workflowPainter = new WorkflowPainter( gc, workflowMeta, maximum, null, null, null, null, null, new ArrayList<AreaOwner>(), 32, 1, 0, "Arial", 10, 1.0d );
  workflowPainter.setMagnification( magnification );
  workflowPainter.drawWorkflow();

  // convert to SVG
  //
  StringWriter stringWriter = new StringWriter();
  graphics2D.stream( stringWriter, true );

  return stringWriter.toString();
}
 
Example #3
Source File: GetPipelineImageServlet.java    From hop with Apache License 2.0 6 votes vote down vote up
private String generatePipelineSvgImage( PipelineMeta pipelineMeta ) throws Exception {
  float magnification = ZOOM_FACTOR;
  Point maximum = pipelineMeta.getMaximum();
  maximum.multiply( magnification );

  DOMImplementation domImplementation = GenericDOMImplementation.getDOMImplementation();

  // Create an instance of org.w3c.dom.Document.
  String svgNamespace = "http://www.w3.org/2000/svg";
  Document document = domImplementation.createDocument(svgNamespace, "svg", null);

  HopSvgGraphics2D graphics2D = new HopSvgGraphics2D( document );

  SvgGc gc = new SvgGc( graphics2D, new Point(maximum.x+100, maximum.y+100), 32, 0, 0 );
  PipelinePainter pipelinePainter = new PipelinePainter( gc, pipelineMeta, maximum, null, null, null, null, null, new ArrayList<>(), 32, 1, 0, "Arial", 10, 1.0d );
  pipelinePainter.setMagnification( magnification );
  pipelinePainter.buildPipelineImage();

  // convert to SVG
  //
  StringWriter stringWriter = new StringWriter();
  graphics2D.stream( stringWriter, true );

  return stringWriter.toString();
}
 
Example #4
Source File: PIDEF0painter.java    From ramus with GNU General Public License v3.0 6 votes vote down vote up
private void writeSVG(OutputStream stream) throws IOException {
    DOMImplementation impl = GenericDOMImplementation
            .getDOMImplementation();
    String svgNS = "http://www.w3.org/2000/svg";
    Document myFactory = impl.createDocument(svgNS, "svg", null);

    SVGGeneratorContext ctx = SVGGeneratorContext.createDefault(myFactory);
    ctx.setEmbeddedFontsOn(Options.getBoolean("EMBEDDED_SVG_FONTS", true));
    SVGGraphics2D svgGenerator = new SVGGraphics2D(ctx, Options.getBoolean(
            "EMBEDDED_SVG_FONTS", true));

    svgGenerator.setSVGCanvasSize(size);

    paint(svgGenerator, 0, 0);

    boolean useCSS = true;
    Writer out = new OutputStreamWriter(stream, "UTF-8");
    svgGenerator.stream(out, useCSS);

}
 
Example #5
Source File: GraphicsParser.java    From tephra with MIT License 6 votes vote down vote up
private boolean clip(Matrix matrix, PDImageXObject pdImageXObject) throws IOException {
    if (clipTypes.isEmpty() || (clipTypes.size() == 1 && clipTypes.get(0).equals("rect")
            && Math.abs(matrix.getScaleX() / matrix.getScalingFactorY()
            - (clipArea[2] - clipArea[0]) / (clipArea[3] - clipArea[1])) <= 0.01D))
        return false;

    SVGGraphics2D svgGraphics2D = new SVGGraphics2D(GenericDOMImplementation.getDOMImplementation()
            .createDocument(SVGDOMImplementation.SVG_NAMESPACE_URI, "svg", null));
    if (pdImageXObject != null) {
        int w = (int) matrix.getScalingFactorX();
        int h = (int) matrix.getScalingFactorY();
        svgGraphics2D.clip(getPath(clipTypes, clipPoints, clipArea));
        svgGraphics2D.drawImage(pdImageXObject.getImage().getScaledInstance(w, h, Image.SCALE_SMOOTH),
                (int) (matrix.getTranslateX() - clipArea[0]), (int) (matrix.getTranslateY() - clipArea[1]), w, h, null);
    }
    save(svgGraphics2D, clipArea[0], clipArea[1], (clipArea[2] - clipArea[0]), (clipArea[3] - clipArea[1]));

    return true;
}
 
Example #6
Source File: ShollAnalysisDialog.java    From SNT with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Exports a JFreeChart to a SVG file.
 *
 * @param chart
 *            JFreeChart to export
 * @param bounds
 *            the dimensions of the viewport
 * @param svgFile
 *            the output file.
 * @throws IOException
 *             if writing the svgFile fails.
 *
 *             This method is taken from:
 *             http://dolf.trieschnigg.nl/jfreechart/
 */
void exportChartAsSVG(final JFreeChart chart, final Rectangle bounds, final File svgFile) throws IOException {

	// Get a DOMImplementation and create an XML document
	final DOMImplementation domImpl = GenericDOMImplementation.getDOMImplementation();
	final Document document = domImpl.createDocument(null, "svg", null);

	// Create an instance of the SVG Generator
	final SVGGraphics2D svgGenerator = new SVGGraphics2D(document);

	// draw the chart in the SVG generator
	chart.draw(svgGenerator, bounds);

	// Write svg file
	final OutputStream outputStream = new FileOutputStream(svgFile);
	final Writer out = new OutputStreamWriter(outputStream, "UTF-8");
	svgGenerator.stream(out, true /* use css */);
	outputStream.flush();
	outputStream.close();
}
 
Example #7
Source File: ParseTreeContextualMenu.java    From intellij-plugin-v4 with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
private static void exportToSvg(UberTreeViewer parseTreeViewer, File file, boolean useTransparentBackground) {
    DOMImplementation domImpl = GenericDOMImplementation.getDOMImplementation();
    Document document = domImpl.createDocument("http://www.w3.org/2000/svg", "svg", null);
    SVGGraphics2D svgGenerator = new SVGGraphics2D(document);

    if (!useTransparentBackground) {
        svgGenerator.setColor(JBColor.WHITE);
        svgGenerator.fillRect(0, 0, parseTreeViewer.getWidth(), parseTreeViewer.getHeight());
    }
    parseTreeViewer.paint(svgGenerator);

    try {
        svgGenerator.stream(file.getAbsolutePath(), true);
    } catch (SVGGraphics2DIOException e) {
        Logger.getInstance(ParseTreeContextualMenu.class)
                .error("Error while exporting parse tree to SVG file " + file.getAbsolutePath(), e);
    }
}
 
Example #8
Source File: PlotUtils.java    From Scripts with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Exports a JFreeChart to a SVG file using the
 * <a href= "http://xmlgraphics.apache.org/batik/" target="_blank">Batik SVG
 * Toolkit</a>, bundled with Fiji. This method is taken from
 * {@literal http://dolf.trieschnigg.nl/jfreechart/}
 *
 * @param chart
 *            the <a href= "http://javadoc.imagej.net/JFreeChart/" target=
 *            "_blank">JFreeChart </a> to export.
 * @param bounds
 *            the Rectangle delimiting the boundaries within which the chart
 *            should be drawn.
 * @param file
 *            the output (destination) file.
 * @throws IOException
 *             if writing to output file fails.
 * @see #exportChartAsSVG(JFreeChart, Rectangle)
 * @see #exportChartAsPDF(JFreeChart, Rectangle)
 * @see #exportChartAsPDF(JFreeChart, Rectangle, File)
 */
public static void exportChartAsSVG(final JFreeChart chart, final Rectangle bounds, final File file)
		throws IOException {

	// Get a DOMImplementation and create an XML document
	final DOMImplementation domImpl = GenericDOMImplementation.getDOMImplementation();
	final org.w3c.dom.Document document = domImpl.createDocument(null, "svg", null);

	// Create an instance of the SVG Generator
	final SVGGraphics2D svgGenerator = new SVGGraphics2D(document);

	// draw the chart in the SVG generator
	chart.draw(svgGenerator, bounds);

	// Write svg file
	final OutputStream outputStream = new FileOutputStream(file);
	final Writer out = new OutputStreamWriter(outputStream, "UTF-8");
	svgGenerator.stream(out, true /* use css */);
	outputStream.flush();
	outputStream.close();
}
 
Example #9
Source File: IDSrendService.java    From han3_ji7_tsoo1_kian3 with GNU Affero General Public License v3.0 6 votes vote down vote up
public void 字組成svg(String 組字式, OutputStream 輸出檔案)
		throws UnsupportedEncodingException, SVGGraphics2DIOException
{
	DOMImplementation domImpl = GenericDOMImplementation
			.getDOMImplementation();

	// Create an instance of org.w3c.dom.Document.
	String svgNS = "http://www.w3.org/2000/svg";
	Document document = domImpl.createDocument(svgNS, "svg", null);

	boolean useCSS = true; // we want to use CSS style
							// attributes
	// Create an instance of the SVG Generator.
	SVGGraphics2D svgGenerator = new SVGGraphics2D(document);
	svgGenerator.setSVGCanvasSize(new Dimension(字型大細, 字型大細));
	組字(組字式, svgGenerator);
	OutputStreamWriter svgOutput = new java.io.OutputStreamWriter(輸出檔案,
			"UTF-8");
	svgGenerator.stream(svgOutput, useCSS);
	return;
}
 
Example #10
Source File: SVGEmitter.java    From maze-harvester with GNU General Public License v3.0 5 votes vote down vote up
public void emit(SegmentPainter painter) throws IOException {
  DOMImplementation domImpl = GenericDOMImplementation.getDOMImplementation();

  // Create an instance of org.w3c.dom.Document.
  String svgNS = "http://www.w3.org/2000/svg";
  Document document = domImpl.createDocument(svgNS, "svg", null);

  // Create an instance of the SVG Generator.
  SVGGraphics2D svgGenerator = new SVGGraphics2D(document);
  SegmentSorter segmentSorter = new SegmentSorter();
  segmentSorter.collect(painter);

  computeBounds(segmentSorter.getBounds());
  svgGenerator.setSVGCanvasSize(
    new Dimension((int) paperSizePixels.getX(), (int) paperSizePixels.getY()));

  // white background (before the maze-coordinates transform)
  svgGenerator.setPaint(Color.WHITE);
  svgGenerator.fill(
      new Rectangle2D.Double(
          0, 0, paperSizePixels.getX(), paperSizePixels.getY()));

  // Set up the page transform so painters can paint in their
  // Room/Door coordinate system.
  svgGenerator.scale(scalePixelsPerRoom, scalePixelsPerRoom);
  svgGenerator.translate(-pageOffsetRooms.getX(), -pageOffsetRooms.getY());

  // Paint segments into the SVG
  segmentSorter.paint(svgGenerator);

  // Finally, stream out SVG to the standard output using
  // UTF-8 encoding.
  boolean useCSS = true; // we want to use CSS style attributes
  OutputStream outputStream = new FileOutputStream(outputFilename);
  Writer out = new OutputStreamWriter(outputStream, "UTF-8");
  svgGenerator.stream(out, useCSS);
}
 
Example #11
Source File: GeometryImpl.java    From tephra with MIT License 5 votes vote down vote up
private void parseGeometry(ReaderContext readerContext, XSLFSimpleShape xslfSimpleShape, JSONObject shape) throws IOException {
    SVGGraphics2D svgGraphics2D = new SVGGraphics2D(GenericDOMImplementation.getDOMImplementation()
            .createDocument(SVGDOMImplementation.SVG_NAMESPACE_URI, "svg", null));
    Rectangle2D rectangle2D = xslfSimpleShape.getAnchor();
    xslfSimpleShape.draw(svgGraphics2D, new Rectangle2D.Double(0.0D, 0.0D, rectangle2D.getWidth(), rectangle2D.getHeight()));
    Element root = svgGraphics2D.getRoot();
    double[] viewBox = getViewBox(xslfSimpleShape);
    root.setAttribute("viewBox", "0 0 " + (viewBox == null ? (rectangle2D.getWidth() + " " + rectangle2D.getHeight())
            : (viewBox[0] + " " + viewBox[1])));

    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    svgGraphics2D.stream(root, new OutputStreamWriter(outputStream, StandardCharsets.UTF_8), false, false);
    svgGraphics2D.dispose();
    outputStream.flush();
    outputStream.close();

    String svg = outputStream.toString().trim()
            .replaceAll("\\s+", " ")
            .replaceAll(" >", ">")
            .replaceAll("> <", "><")
            .replaceAll("<text [^>]+>[^<]*</text>", "")
            .replaceAll("<g [^>]+></g>", "");
    if (!svg.contains("<path "))
        return;

    ByteArrayInputStream inputStream = new ByteArrayInputStream(svg.getBytes());
    String geometry = readerContext.getMediaWriter().write(MediaType.Svg, "geometry.svg", inputStream);
    inputStream.close();

    shape.put("geometry", geometry);
}
 
Example #12
Source File: AbstractSvgTest.java    From jasperreports with GNU Lesser General Public License v3.0 4 votes vote down vote up
@Override
protected void export(JasperPrint print, OutputStream out) throws JRException, IOException
{
	DOMImplementation domImpl = GenericDOMImplementation.getDOMImplementation();
	Document document = domImpl.createDocument(null, "svg", null);
	SVGGraphics2D grx = 
		new SVGGraphics2D(
			SVGGeneratorContext.createDefault(document), 
			false // this is for textAsShapes, but does not seem to have effect in our case
			);
	
	JRGraphics2DExporter exporter = new JRGraphics2DExporter();
	
	exporter.setExporterInput(new SimpleExporterInput(print));
	SimpleGraphics2DExporterOutput output = new SimpleGraphics2DExporterOutput();
	Graphics2D g = (Graphics2D)grx.create();
	output.setGraphics2D(g);
	exporter.setExporterOutput(output);
	
	for (int pageIndex = 0; pageIndex < print.getPages().size(); pageIndex++)
	{
		g.translate(0,  pageIndex * print.getPageHeight());
		
		SimpleGraphics2DReportConfiguration configuration = new SimpleGraphics2DReportConfiguration();
		configuration.setPageIndex(pageIndex);
		exporter.setConfiguration(configuration);

		exporter.exportReport();
	}
	
	ByteArrayOutputStream baos = new ByteArrayOutputStream();
	// use OutputStreamWriter instead of StringWriter so that we have "encoding" attribute in <xml> header tag.
	grx.stream(new OutputStreamWriter(baos, "UTF-8"), true);
	
	SVGTranscoder transcoder = new SVGTranscoder();
	transcoder.addTranscodingHint(SVGTranscoder.KEY_NEWLINE, SVGTranscoder.VALUE_NEWLINE_LF);
	try
	{
		transcoder.transcode(
			new TranscoderInput(new InputStreamReader(new ByteArrayInputStream(baos.toByteArray()), "UTF-8")), 
			new TranscoderOutput(new OutputStreamWriter(out, "UTF-8"))
			);
	}
	catch (TranscoderException e)
	{
		throw new JRException(e);
	}
	
	out.close();
}
 
Example #13
Source File: SVG.java    From OSPREY3 with GNU General Public License v2.0 4 votes vote down vote up
public SVG() {

		// make the SVG DOM
		doc = (GenericDocument)GenericDOMImplementation.getDOMImplementation().createDocument(
			"http://www.w3.org/2000/svg",
			"svg",
			null
		);

		// get the graphics object that makes SVG DOM elements
		ctx = SVGGeneratorContext.createDefault(doc);
		ctx.setStyleHandler((Element elem, Map styleMap, SVGGeneratorContext ctxAgain) -> {

			// don't modify <g> elements
			if (elem.getTagName().equalsIgnoreCase("g")) {
				return;
			}

			// set the current style classes, if any
			if (currentStyleClasses != null && !currentStyleClasses.isEmpty()) {
				elem.setAttribute(SVGConstants.SVG_CLASS_ATTRIBUTE, StyleClass.renderNames(currentStyleClasses));
			}

			// set the current id, if any
			if (currentId != null) {
				elem.setAttribute(SVGConstants.SVG_ID_ATTRIBUTE, currentId);
			}
		});
		g = new SVGGraphics2D(ctx, false);

		// HACKHACK: get some internal stuff using reflection so we can add SVG elements directly
		try {
			Field groupsField = g.getClass().getDeclaredField("domGroupManager");
			groupsField.setAccessible(true);
			groups = (DOMGroupManager)groupsField.get(g);
		} catch (Throwable t) {
			throw new Error("Reflection hacks failed, maybe the Batik version changed?", t);
		}

		// set the default bonuds
		setBounds(0, 100, 0, 100);
	}