Write SVG files with Processing.org





It is possible to use Processing's XML functionality to write SVG files.  Here is a simple function that will save a bezier curve in SVG format with the call writeXML( "mySVG.svg");  It will create an SVG file with the bare minimum of data.  Hopefully you can extrapolate how to draw multiple shapes, and it would also be of benefit to look at a specification for SVG path's and other elements (such as this one):





void writeSVG( String filename ) {
   XML new_file;      // file handle
   XML element;       // for SVG shapes within file
   String buf;        // string buffer  
   PVector anchor0;   // bezier points
   PVector control0;
   PVector control1;
   PVector anchor1;


   // This sets the appropriate flag for 
   // inkscape or illustrator to read the file.
   new_file = new XML("svg");

   // Set up our bezier curve points.
   // These coordinates are just for
   // a demonstration.
   anchor0  = new PVector(  0, 20 );
   control0 = new PVector(  0,  0 );
   control1 = new PVector( 40, 40 );
   anchor1  = new PVector( 30, 20 );
   
   // Set our element to a path
   element = new XML("path"); 

   // construct the data string of the element
   buf  = "M ";
   buf += anchor0.x  + "," + anchor0.y;
   buf += " C";
   buf += control0.x + "," + control0.y;
   buf += " ";
   buf += control1.x + "," + control1.y;
   buf += " ";
   buf += anchor1.x  + "," + anchor1.y;
   
   // Set the data string in element
   element.setString( "d", buf );

   // construct the style string of the element
   buf = "fill:none;stroke:#000000";

   // set the style string in element
   element.setString( "style", buf );

   // set the id of the path in element
   element.setString( "id", "path0" );

   // Write element to the SVG file
   new_file.addChild( element );


   // save the changes.
   saveXML( new_file, filename );

}