I want to convert the SVG file into image. The problem is my SVG use the external CSS file and when I use Apache Batik, it can not recognize the external CSS file, and it just shows the styles which are inline the SVG tags. Here is my sample code:
public static void svg2jpgBatik1() {
JPEGTranscoder transcoder = new JPEGTranscoder();
try {
// Create a JPEG transcoder
JPEGTranscoder t = new JPEGTranscoder();
// Set the transcoding hints.
t.addTranscodingHint(JPEGTranscoder.KEY_QUALITY,
0.8f);
// Create the transcoder input.
String svgURI = new File("D:\\SVG_PATH\\map.svg").toURL().toString();
TranscoderInput input = new TranscoderInput(svgURI);
// Create the transcoder output.
OutputStream ostream = new FileOutputStream("D:\\JPEG_PATH\\map.jpg");
TranscoderOutput output = new TranscoderOutput(ostream);
t.addTranscodingHint(JPEGTranscoder.KEY_ALTERNATE_STYLESHEET, "D:\\STYLESHEET_PATH\\style.css");
t.addTranscodingHint(JPEGTranscoder.KEY_BACKGROUND_COLOR, Color.blue);
// Save the image.
t.transcode(input, output);
// Flush and close the stream.
ostream.flush();
ostream.close();
} catch (Exception e) {
e.printStackTrace();
}
}
This line works :
t.addTranscodingHint(JPEGTranscoder.KEY_BACKGROUND_COLOR, Color.blue);
while this line doesn't work :
t.addTranscodingHint(JPEGTranscoder.KEY_ALTERNATE_STYLESHEET, "D:\\STYLESHEET_PATH\\style.css");
into the SVG I've added this part :
<svg id="Layer_1" data-name="Layer 1" xmlns="http://www.w3.org/2000/svg" width="100%" height="100%" viewBox="0 0 10 1000" preserveAspectRatio="xMinYMin meet">
<defs>
<link href="STYLESHEET_PATH\\style.css" type="text/css" rel="stylesheet"
xmlns="http://www.w3.org/1999/xhtml"/>
</defs>
Which applied the SVG when I open it in the browser but in batik it doesn't apply.
I also put the styles into the tag in the SVG, but the result was the same.
The only style it could apply is the inline SVG style such as fill="#FFFFFF":
<text text-anchor="middle" alignment-baseline="middle" x="624" xml:space="preserve" y="123.0"
fill="#FFFFFF" >Sample Text</text>
I was wondering if anyone could help me to solve this problem or let me know any best alternatives for having styles for SVG from External CSS when I convert it to an image.
Thanks in advance.
I've added this line at the top of my SVG code :
instead of this part after the SVG tag:
and now it makes the image with styles from the external CSS file.
So the SVG file would be :