I have a working example of exporting a selected symbol to an SVG string in Sketch 3. (Based on this code from Sketch's GitHub)
The issue is the output is distorted and I'm unable to see the next logical step in troubleshooting.
The Code
// Get all symbols
var symbols = context.document.documentData().allSymbols();
// For purpose of this example, only get the first one for testing.
var symbol = symbols[0];
// Set a temporary file to save to. Necessary for generating the SVG
var tempPath = '/tmp/com.symbolui.sketch-commands/';
var guid = [[NSProcessInfo processInfo] globallyUniqueString];
var path = tempPath + guid;
[[NSFileManager defaultManager] createDirectoryAtPath:path withIntermediateDirectories:true attributes:nil error:nil]
var export_path = path;
var export_filename = export_path + '/' + 'test.svg';
// do export
[doc saveArtboardOrSlice:frame toFile:export_filename];
var file_url = [NSURL fileURLWithPath:export_filename];
var str = [[NSString alloc] initWithContentsOfURL:file_url];
At the final point in the code, str
is a text value of the SVG generated from the symbol.
The Output
Input Symbol:
Generated preview of SVG:
Generated SVG text:
<?xml version="1.0" encoding="UTF-8"?>
<svg width="1200px" height="65px" viewBox="0 0 1200 65" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
<!-- Generator: Sketch 42 (36781) - http://www.bohemiancoding.com/sketch -->
<title></title>
<desc>Created with Sketch.</desc>
<defs>
<rect id="path-1" x="0" y="0" width="49" height="20" rx="3"></rect>
<mask id="mask-2" maskContentUnits="userSpaceOnUse" maskUnits="objectBoundingBox" x="0" y="0" width="49" height="20" fill="white">
<use xlink:href="#path-1"></use>
</mask>
</defs>
<g id="Symbols:-Labels" stroke="none" stroke-width="1" fill="none" fill-rule="evenodd">
<g id="Buttons" transform="translate(-422.000000, 31.000000)"></g>
<g id="Label-/-Default" transform="translate(670.000000, 60.000000)">
<use id="background" stroke="#979797" mask="url(#mask-2)" stroke-width="2" fill="#777777" xlink:href="#path-1"></use>
<text id="-Default" font-family="HelveticaNeue-Bold, Helvetica Neue" font-size="10" font-weight="bold" fill="#FFFFFF">
<tspan x="7" y="14">Default</tspan>
</text>
</g>
</g>
Thoughts
As you can see the output is quite large in addition to being distorted. At the very least I believe I need to trim or rescale the symbol somehow. Where the distortion is coming through I have no idea.
Fixing the SVG markup itself isn't a solution - I'd like to see the solution in the Sketch plugin code. I'm finding documentation for internal Sketch code very difficult to work with and has been the big blocker for resolving this.
you can convert the
MSSymbolInstance
to normal group, then export it.