I want
  1. To manipulate a svg-document and then export it to svg file
  2. Then manipulate existing svg-document again and export it second time to a svg file and so on...

I noticed that after a svg-document was exported to an svg file with svgGenerator.stream(streamWriter, useCss) method the svg document become empty.

Can some body give me a hint, what is wrong in my code?

I posted my question on stack-overflow, but didn't get any answer, so you are my last hope :-)

public void svgExportExample() {

  final SVGGraphics2D svgGenerator = createSvgGenerator();



  final String xml1 = toXml(svgGenerator);

  final String xml2 = toXml(svgGenerator);

  assertEquals("xml document was not changed and should be the same",
    xml1, xml2);


private SVGGraphics2D createSvgGenerator() {
  final Document document = initNewDocument();

  final SVGGraphics2D svgGenerator = new SVGGraphics2D(document);
  return svgGenerator;

private Document initNewDocument() {
  // Get a DOMImplementation.
  final DOMImplementation domImpl = GenericDOMImplementation

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

private String toXml(final SVGGraphics2D svgGenerator) {

  try (ByteArrayOutputStream os = new ByteArrayOutputStream(); OutputStreamWriter streamWriter = new OutputStreamWriter(os)) {

    final boolean useCss = true;
    // this method clears the content of the xnl-document
    svgGenerator.stream(streamWriter, useCss);

    return os.toString(StandardCharsets.UTF_8.name());

  } catch (final IOException e) {
    throw new IllegalStateException(
      "a proble during printing to svg file was occured", e);


private void drawText(final Graphics2D g) {
  final String text = "My Text inside Svg";
  final int fontSize = 10;
  final int width = 10;
  final int height = 10;
  final Graphics g1 = new BufferedImage(width, height,
  final int style = 0;
  final Font font = new Font(g1.getFont().toString(), style, fontSize);



  g.drawString(text, 50, 100);

private void drawRectangle(final Graphics2D g) {
  final int width = 500;
  final int height = 300;
  g.fillRect(0, 0, width, height);