svg - How to determine text width and height when using svgwrite for python? -
svg - How to determine text width and height when using svgwrite for python? -
i want extract pixel size of text object (svgwrite.drawing.text) appear in file after formatting given style. font fixed-width (courier new).
the reason why need want print svg file string , map on resulting text information: e.g. have string "abcdef" , external wise man told me "bcd" portion should marked. need know how many pixels (units?) covered symbol "a" , symbols "bcd" in both dimensions, , draw colored rectangle, or transparent frame, or whatever strictly under "bcd" portion.
so have next code , expect utilize "w = text1.width" extract width, doesn't work way. give thanks in advance trying reply question.
import svgwrite my_svg = svgwrite.drawing(filename = "dasha.svg", size = ("800px", "600px")) text_style = "font-size:%ipx; font-family:%s" % (12, "courier new") text1 = my_svg.text("hello world", insert=(0, 0), fill="black", style=text_style) my_svg.add(text1) my_svg.save()
upd1 [22.06.2014]: intermediate solution utilize @ moment measure height , width of letter particular font , size manually in inkscape. tried best, not sure such values perfect, , can't alter font size in program.
i had exact same problem, had variable width font. solved taking text element (correct font , content) wanted, wrote svg file, , used inkscape installed on pc render drawing temporary png file. read dimensions of png file (extracted header), removed temp svg , png files , used result place text wanted , elements around it.
i found rendering drawing, using dpi of 90 seemed give me exact numbers needed, or native numbers used in svgwrite whole. -d flag utilize drawable element, i.e. text, rendered.
os.cmd(/cygdrive/c/program\ files\ \(x86\)/inkscape/inkscape.exe -f work_temp.svg -e work_temp.png -d 90 -d)
i used these functions extract png numbers, found @ link, note mine corrected python3 (still working in python2)
def is_png(data): homecoming (data[:8] == b'\x89png\r\n\x1a\n'and (data[12:16] == b'ihdr')) def get_image_info(data): if is_png(data): w, h = struct.unpack('>ll', data[16:24]) width = int(w) height = int(h) else: raise exception('not png image') homecoming width, height if __name__ == '__main__': open('foo.png', 'rb') f: info = f.read() print is_png(data) print get_image_info(data)
it's clunky, worked
python svg
Comments
Post a Comment