Search code examples
javatomcatsvgpngbatik

Java code to convert SVG to PNG with UTF-8 character


I am using below code to create PNG from SVG file and write it to Servlet output stream. The SVG file is having UTF-8(Japanese) characters in AXIS name.

ServletOutputStream out = response.getOutputStream();
InputStream svgFileStream = new FileInputStream(svgFile);
TranscoderInput inputSvgImage = new TranscoderInput(svgFileStream);
PNGTranscoder converter = new PNGTranscoder();
TranscoderOutput outputPngImage = new TranscoderOutput(out);
converter.transcode(inputSvgImage, outputPngImage);

The above code is working fine in my local but when I upload it to the server it shows squares instead of character. When there is English character instead of Japanese it works fine on both local as well as server.

Can you please let me know if you have faced same issue. Can it be related to Tomcat ?

I have checked SVG file from server, UTF-8 characters are visible in it. I also tried InputStreamReader instead of InputStream with "UTF-8" but did not work.

As per one response found I tried Write instead of ServletOutputStream with "UTF-8" in TranscoderOutput but it did not create any image.

Thanks


Solution

  • UPDATE

    As far as it is working correctly on your local and you serve a png image as a result, it has to be independent from application server's encoding configuration, and your svg file itself is correctly encoded I do not think it is an encoding issue.

    @Eugene K. yes there is a possibility that some java classes uses the os default locale implicitly but I can not reproduce the problem with the same code given in question although I do not have Japanese locale. IMHO it is highly probable that server has some missing fonts installed.

    It may not be an elegant way and also does not related with Java but as a solution if you have a chance to edit your source svg file somehow which it can also be dynamically with some string manipulation if you ever need, you can provide a font which includes Japanese characters and serve it from your servlet. Then add these to your svg file and specify a font family for your text:

    <defs>
      <style type="text/css">
      <![CDATA[
      @font-face {
        font-family: Somefont;
        src: url('http://localhost:8080/Somefont.ttf');
      }
      ]]>
      </style>
    </defs>
    <text font-family="Somefont" font-size="40" fill="blue">Text for test!</text>
    

    Hope it helps!