问题
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?
回答1:
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.
回答2:
Just add the following element as a child of <svg/>
: <style type="text/css">
Then, similar to HTML...
来源:https://stackoverflow.com/questions/11851821/how-i-use-a-custom-font-with-the-batik-svg-library