【发布时间】:2018-08-10 12:32:54
【问题描述】:
我正在使用 Batik 将 SVG 转换为 PNG 图像,但多行文本无法正确呈现。文本本身不再以最终图像为中心可能会以一种不确定的方式发生。
例如,考虑开始 SVG 的这一部分:
这是正确的渲染,我也希望在 PNG 中获得。顺便说一下,生成的 PNG 如下所示:
如您所见,顶部绿色框中的文本不再居中。
这是定义它的 SVG 片段(怀疑是字体问题,我也尝试删除所有 font-family="",但没有任何效果):
<g transform="translate(184.68 -0.600364)">
<text fill="rgb(255, 255, 255)" fill-opacity="1" font-family="Kievit Pro" font-size="10px" font-style="normal" font-weight="normal" text-anchor="middle" transform="translate(48 0.429996)">
<tspan dy="1em" x="0">A simple activity, with</tspan>
<tspan dy="1.5em" x="0">a text that goes on t</tspan>
</text>
</g>
如果有帮助,这是我用于转换的代码:
static byte[] convertToPng(byte[] byteSvgSmall) throws TranscoderException, IOException {
if (byteSvgSmall != null) {
byte[] byteImagePng = null;
ByteArrayInputStream bais = null;
ByteArrayOutputStream baos = new ByteArrayOutputStream();
InputStream targetStream = null;
try {
targetStream = new ByteArrayInputStream(byteSvgSmall);
TranscoderInput input = new TranscoderInput(targetStream);
PNGTranscoder transcoder = new PNGTranscoder();
transcoder.addTranscodingHint(PNGTranscoder.KEY_WIDTH, new Float(diagramWidthInPixelsForPdf));
TranscoderOutput output = new TranscoderOutput(baos);
transcoder.transcode(input, output);
byte[] byteOutput = baos.toByteArray();
byteImagePng = new byte[byteOutput.length];
bais = new ByteArrayInputStream(baos.toByteArray());
bais.read(byteImagePng);
targetStream.close();
baos.flush();
return byteImagePng;
} catch (Exception e) {
BeanFactory
.getLogger()
.error(SVGTransformer.class,
"An error occurred. A null byte[] will be returned",
e);
return null;
} finally {
if (bais != null) bais.close();
if (baos != null) baos.close();
if (targetStream != null) targetStream.close();
}
}
return null;
}
然后,使用返回的字节[]:
if (pngBytes != null) {
BufferedImage final_img = ImageIO.read(new ByteArrayInputStream(pngBytes));
File output_file = new File(imagepath);
ImageIO.write(final_img, "png", output_file);
}
非常感谢您提供任何见解。
【问题讨论】:
-
@Andreaジーティーオー 我无法重现该问题。我正在使用 1.9.1
org.apache.xmlgraphics batik-all 1.9.1版本> pom -
@EzekielBaniaga:非常感谢您的尝试,非常感谢。也响应 Dave Jarvis,我正在使用 Java 1.6 进行编译,batik-all-1.7.jar;我不知道哪个工具生成了 SVG;我从另一个团队收到它,以便使用 Apache POI 将其放入 PDF。