Last active
June 29, 2017 14:05
-
-
Save macfire/15b3907617f05180f386b03b29c44e45 to your computer and use it in GitHub Desktop.
Convert a folder of individual SVG icon files to a SVG symbol library embedded in HTML document. Includes a bullet list of the symbols.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# -*- coding: utf-8 -*- | |
""" | |
create_svg_symbol_library.py | |
~~~~~~~~~~~~~~~~~~~ | |
:copyright: (c) 2016 by Jerry McCreary. | |
:license: MIT | |
Convert a folder of individual SVG icon files to a SVG symbol library | |
embedded in HTML document. Includes a bullet list of the symbols. | |
Currently, the script only pulls in <path> tags. | |
Depends on icons being prepared using compound paths instead of grouped objects. | |
If this doesn't meet your needs, fork and modify. | |
""" | |
import os,fnmatch #re, glob, | |
from bs4 import BeautifulSoup | |
path_base = '/path/to/root/folder/' | |
path_images = '%s%s' % (path_base, 'images/') | |
html_file_name = 'my_svg_symbols.html' | |
symbol_color = '#000000' | |
html_head = """ | |
<!DOCTYPE html> | |
<html lang="en"> | |
<head> | |
<meta charset="UTF-8"> | |
<title>Symbols</title> | |
<style> | |
.icons [class*="svg-icon__"] { | |
height: 64px; | |
width: 64px; | |
fill: %s; | |
margin-right: 5px; | |
vertical-align: middle; | |
} | |
</style> | |
</head> | |
<body> | |
<div class="icons"> | |
<ul> | |
""" % symbol_color | |
html_middle = """ | |
</ul> | |
</div> | |
<svg xmlns="http://www.w3.org/2000/svg" style="display: block;"> | |
""" | |
html_foot = """ | |
</svg> | |
</body> | |
</html> | |
""" | |
html_ul = "" | |
html_svg = "" | |
for filename in os.listdir(path_images): | |
if fnmatch.fnmatch(filename,'*.svg'): | |
f = os.path.splitext(filename)[0] | |
li = "<li><svg aria-hidden='true' class='svg-icon__%s'><use xlink:href='#%s'></use></svg>%s</li>\n" % (f,f,f) | |
html_ul = "%s%s" % (html_ul, li) | |
path_str = "" | |
svg_dom = BeautifulSoup(open(path_images + filename), "html.parser") | |
paths = svg_dom.find_all('path') | |
for path in paths: | |
path_str = "%s%s" % (path_str,path) | |
symbol = "<symbol id='%s' viewbox='0 0 512 512'><title>%s</title>%s</symbol>\n" % (f,f,path_str) | |
html_svg = "%s%s" % (html_svg,symbol) | |
html = "%s %s %s %s %s" % (html_head,html_ul,html_middle,html_svg,html_foot) | |
#print(html) | |
target_file = path_base + html_file_name | |
with open(target_file,"w") as text_file: | |
print(html,file=text_file) | |
text_file.close() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment