Background
There are number of unanswered questions related to reading and parsing SVG paths:
- Easiest way to read in svg path data with Java?
- Re: parsing a svg file using batik svg parser
- https://stackoverflow.com/questions/16672100
- How to convert SVG Path (SVGOMPathElement) to array of points?
This question and answer aims to resolve all these questions.
Problem
The SVG path
element contains a data attribute (d
). Sometimes it is necessary to load, parse, and extract just the path information from an SVG file.
Question
How do you load, parse, and extract SVG path information from an SVG file using Java?
Overview
Load and parse SVG files using Apache Batik. The solution shows Java code in the preliminary stages of converting an SVG file to MetaPost. This should provide a general idea for how to load, parse, and extract content from SVG files using Java.
Libraries
You will need the following libraries:
Load SVG File
The main application loads the SVG file into DOM, then converts the DOM to an SVG DOM. The
initSVGDOM()
method call is extremely important. Without callinginitSVGDOM()
, the methods for extracting SVG DOM elements from the DOM would not be available.Note: Calling
initSVGDOM()
should be Batik's default behaviour unless otherwise specified. Alas, it isn't, and discovering this gem means reading documentation buried on their website.Parse SVG DOM
Parsing the SVG DOM is then relatively trivial. The
toCode()
method is the workhorse of the class:Build
Compiling will vary from environment to environment. A script similar to the following should help:
Be sure to put all the
.jar
files into the./lib
directory. Put the source files into the./source
directory.Run
Create a script (or batch file) to execute the program:
Output
When run against a file containing a valid SVG path, this produces:
From here it should be clear how to read SVG path data into their corresponding SVG objects using Java.
Addendum
Note that the simplest way to convert from SVG to MetaPost is:
pstoedit
.