Skip to content

Instantly share code, notes, and snippets.

@vicapow
Last active April 5, 2023 12:45
Show Gist options
  • Save vicapow/5a1e4595d4b9e7e04a20 to your computer and use it in GitHub Desktop.
Save vicapow/5a1e4595d4b9e7e04a20 to your computer and use it in GitHub Desktop.
getStyles function from NYT's Crowbar

Get all the styles as a string from a given document. useful for creating a PNG from an SVG. SVG's need to have all of their style information embedded within their document to be properly exported.

Example usage:

var styles = getStyles(window.document);

Try it by going to [http://bl.ocks.org/vicapow/raw/9904319/](this block) and running the above usage example in the console.

function getStyles(doc) {
var styles = "",
styleSheets = doc.styleSheets;
if (styleSheets) {
for (var i = 0; i < styleSheets.length; i++) {
processStyleSheet(styleSheets[i]);
}
}
function processStyleSheet(ss) {
if (ss.cssRules) {
for (var i = 0; i < ss.cssRules.length; i++) {
var rule = ss.cssRules[i];
if (rule.type === 3) {
// Import Rule
processStyleSheet(rule.styleSheet);
} else {
// hack for illustrator crashing on descendent selectors
if (rule.selectorText) {
if (rule.selectorText.indexOf(">") === -1) {
styles += "\n" + rule.cssText;
}
}
}
}
}
}
return styles;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment