I'm working on a Java program which creates templates for clothes. The user enters the word they want to see on the item of clothing and the system creates a PDF template. To create the template I create an SVG document programatically then use Batik to transcode the SVG to the PDF format.
My client now wants to be able to use custom fonts to create the templates. I was wondering if it's possible to use fonts like a TTF with the Batik transcoder? If so how do you go about setting up the SVG?
Today, the best approach for embedding fonts directly in your SVG file is to use an OpenType-compatible web font, converted to a data URI, as the src URL in a CSS @font-face rule. Nonetheless, think carefully before using a data URI font on the web.
Batik is a pure-Java library that can be used to render, generate, and manipulate SVG graphics (SVG is an XML markup language for describing two-dimensional vector graphics). IBM supported the project and then donated the code to the Apache Software Foundation, where other companies and teams decided to join efforts.
First you need to transform the font file from TTF to SVG with batik's ttf2svg, once you have the converted file you have to add reference in the 'defs' section of your SVG document. this is how i did it:
Element defs = doc.createElementNS(svgNS, "defs");
Element fontface = doc.createElementNS(svgNS, "font-face");
fontface.setAttributeNS(null, "font-family", "DroidSansRegular");
Element fontfacesrc = doc.createElementNS(svgNS, "font-face-src");
Element fontfaceuri = doc.createElementNS(svgNS, "font-face-uri");
fontfaceuri.setAttributeNS(svgNS, "xlink:href", "fonts/DroidSans-webfont.svg#DroidSansRegular");
Element fontfaceformat = doc.createElementNS(svgNS, "font-face-format");
fontfaceformat.setAttributeNS(svgNS, "string", "svg");
fontfaceuri.appendChild(fontfaceformat);
fontfacesrc.appendChild(fontfaceuri);
fontface.appendChild(fontfacesrc);
defs.appendChild(fontface);
svgRoot.appendChild(defs);
when creating the text element set the font family just like any other font
Element txtElem = doc.createElementNS(svgNS, "text");
txtElem.setAttributeNS(svgNS, "style", "font-family:DroidSansRegular;font-size:" + fontsize + ";stroke:#000000;#fill:#00ff00;");
txtElem.setTextContent("some text");
svgRoot.appendChild(txtElem);
i got the info from this article: http://frabru.de/c.php/article/SVGFonts-usage hope it helps.
Just add the following element as a child of <svg/>
: <style type="text/css">
Then, similar to HTML...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With