![](/img/trans.png)
[英]How to transform Graphics2D in SVGGraphics2D using Apache Batik Library?
[英]How can I set a font-family instead of font when using Batik's SVGGraphics2D?
我目前使用 Batik 的 SVGGraphics2D 有以下代码:
...
final SVGGraphics2D svgGraphics2D = new SVGGraphics2D(svgGeneratorContext, false);
svgGraphics2D.setSVGCanvasSize(new Dimension(width, height));
svgGraphics2D.setFont(font);
...
因此,如果font
是执行代码的系统上的可用Font
,则会将正确的属性添加到生成的 SVG 文件中。
但是,如果缺少字体(例如 Linux 机器上的“Verdana”),则使用默认字体(添加了font-family:'Dialog'
)。
因此,我想传递一个字体系列而不是指定字体,以便在生成的 SVG 中使用font-family="DejaVu Sans,Verdana,Geneva,sans-serif"
。 知道如果我没猜错,API 只接受Font
参数,我怎么能做到这一点?
我希望有比使用 xslt 转换 xml 输出更简单的方法。
先感谢您。
如果你有一个(许可的)字体文件,比如资源,你可以这样做:
InputStream is = SomeClass.getResourceAsStream("/fonts/DejaVu Sans.ttf");
Font font = Font.createFont(Font.TRUETYPE_FONT, is);
GraphicsEnvironment.getLocalGraphicsEnvironment();
ge.registerFont(font);
这是交付具有自己字体的应用程序的通用方法。
然后在 SVG 中,您可以为独立的 svg 文件嵌入确切的字体。
我想知道这是不可能的:
font-family="'DejaVu Sans',Verdana,Geneva,sans-serif"
因为那将是 CSS 方式。
给定width
、 height
和 Swing 组件( label
),以下代码将导出一个 SVG 文档,其中viewBox
和font-family
属性设置在根svg
元素上:
final var dom = getDOMImplementation();
final var ns = "http://www.w3.org/2000/svg";
final var doc = dom.createDocument( ns, "svg", null );
final var context = createDefault( doc );
context.setPrecision( 5 );
final var generator = new SVGGraphics2D( context, false );
generator.setSVGCanvasSize( new Dimension( width, height ) );
label.paintComponent( generator );
Element root = generator.getRoot();
final String viewBox = format( "0 0 %d %d", width, height );
root.setAttribute( SVG_VIEW_BOX_ATTRIBUTE, viewBox );
root.setAttribute( "font-family", "Arial" );
try( final var out = new OutputStreamWriter(
new FileOutputStream( "/tmp/saved.svg" ), UTF_8 ) ) {
generator.stream( root, out );
}
产生:
<svg
stroke-dasharray="none"
shape-rendering="auto"
xmlns="http://www.w3.org/2000/svg"
font-family="Arial"
width="305"
text-rendering="auto"
fill-opacity="1"
contentScriptType="text/ecmascript"
color-interpolation="auto"
color-rendering="auto"
preserveAspectRatio="xMidYMid meet"
font-size="12px"
viewBox="0 0 3 3"
fill="black"
xmlns:xlink="http://www.w3.org/1999/xlink"
stroke="black"
image-rendering="auto"
stroke-miterlimit="10"
zoomAndPan="magnify"
version="1.0"
stroke-linecap="square"
stroke-linejoin="miter"
contentStyleType="text/css"
font-style="normal"
height="311"
stroke-width="1"
stroke-dashoffset="0"
font-weight="normal"
stroke-opacity="1">
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.