NSBezierPath to SVG?

There is a method to convert a NSBezierPath to SVG in Python?
Or it is possible to get SVG from a Layer without exporting font file ?

I would like to do something similar to Filter > Glyph as Image > SVG without creating a file but returning <svg>...</svg>

There is an internal class called GSSVGPen that you can use like so:

from AppKit import NSXMLNodePrettyPrint, NSUTF8StringEncoding
GSSVGPen = objc.lookUpClass("GSSVGPen")
pen = GSSVGPen.new()
Layer.drawInPen_(pen)
svgData = pen.svgDoc().XMLDataWithOptions_(NSXMLNodePrettyPrint)
svg = NSString.alloc().initWithData_encoding_(svgData, NSUTF8StringEncoding)
print(svg)
# <svg xmlns="http://www.w3.org/2000/svg">
#    <path ...
#    ...
# </svg>
1 Like

Mmh there is something wrong.

I seem that <svg> ... </svg> generated with your script is not exactly the same as the one export with “Glyph as Image” Filter and is not displayed in HTML page.

Generated with your script:
<svg xmlns="http://www.w3.org/2000/svg">
    <path d="M78-554v358h358v-358Z"></path>
</svg>


Generated with Glyph as Image Filter:
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 600 1000">
    <path d="M78,446v358h358v-358Z"></path>
</svg>

The Glyph as Image filter add the viewBox attribute. So the script needs to do that, too. Didn’t Rainer post a script that was using the filter directly, recently?

1 Like

I found it and modified it to get SVG for a string :

font = Glyphs.font
import time
from AppKit import NSPoint, NSSize

GlyphAsImage = NSClassFromString("GlyphAsImage")

def getSVG(string):

    masterID = font.selectedFontMaster.id

    tempGlyph = GSGlyph()
    tempGlyph.name = "tempGlyph"
    font.glyphs.append(tempGlyph)

    LAYER = font.glyphs["tempGlyph"].layers[masterID]

    xPos = 0

    for c in string:
        comp = GSComponent(c)
        comp.automaticAlignment = False
        comp.position = NSPoint(xPos, 0)
        xPos += font.glyphs[c].layers[masterID].width
        if c != " ":
            font.glyphs['tempGlyph'].layers[masterID].shapes.append(comp)
        
    font.glyphs['tempGlyph'].layers[masterID].width = xPos

    preset = {
        "active": True,
        "name": "SVG",
        "size": LAYER.ascender,
        "factor": 1,
        "format": "SVG"
    }
    layerSize = NSSize(LAYER.width, LAYER.ascender-LAYER.descender)
    svgData = GlyphAsImage.svgDataWithLayer_origSize_settings_(LAYER, layerSize, preset)
    del(font.glyphs['tempGlyph'])

    return svgData

print(getSVG("Hello"))
1 Like