Esempio n. 1
0
def append_svg_to_file(fragment_file, main_file):
    try:
        svg_main = parse(main_file)
        svg_frag = parse(fragment_file)
        for e in svg_frag.getAllElements():
            svg_main.addElement(e)
        svg_main.save(main_file)
    except Exception as e:
        print "Coudlnt' read input file:", fragment_file, e
Esempio n. 2
0
def get_dimensions(svg_file):
    parsed = parse(svg_file)
    #rewind to avoid an error when the file is parsed again
    svg_file.seek(0)
    #this is wrong #FIXME
    #might be 0
    width = parsed.getAttribute('width')
    height = parsed.getAttribute('height')

    #try viewbox
    if width == None or height == None:
        viewbox = parsed.get_viewBox()
        width = viewbox.split(' ')[2]
        height = viewbox.split(' ')[3]
    
    if width == None or height == None:
        #abort!
        raise Exception("couldn't get width or height of uploaded svg")
    pixtomm = 3.55
    #FIXME bad way of handling svg sizes
    if width.endswith("px"):
        width = float(width.rstrip("px"))
    else:
        width = float(width)

    if height.endswith("px"):
        height = float(height.rstrip("px"))
    else:
        height = float(height)

    return (width,height)
Esempio n. 3
0
def convert(file_, image_folder):

    def setAttributes(attrs, obj):
        for attr in attrs.keys():
            if hasattr(obj, parser.calculateMethodName(attr)):
                eval('obj.' + parser.calculateMethodName(attr))(attrs[attr].value)
            else:
                if not hasattr(obj, "_data"):
                    obj._data = {}
                obj._data[attr] = attrs[attr].value
                if not hasattr(obj, "data"):
                    obj.data = lambda key: obj._data.get("data-" + key)

    parser.setAttributes = setAttributes

    svg_file = parser.parse(file_)
    for image in svg_file.getElementsByType(structure.Image):
        try:
            design_image_file = image.data("design-image-file")
            design_image_file = design_image_file.rsplit('/')[-1]
            design_image_full_path = os.path.join(image_folder, design_image_file)

            if os.path.exists(design_image_full_path):
                im = Image.open(design_image_full_path)
                new_im = im.resize((int(float(image.get_width())), int(float(image.get_height()))), Image.ANTIALIAS)
                tmp_file = os.path.join(image_folder, ".tmp".join(os.path.splitext(design_image_file)))
                new_im.save(tmp_file)

                with open(tmp_file, "rb") as f:
                    content = f.read()
                os.unlink(tmp_file)
                image.set_xlink_href("data:image/png;base64," + base64.b64encode(content))
        except AttributeError:
            pass
        svg_file.save(".hd".join(os.path.splitext(file_)))
Esempio n. 4
0
    def test_appending(self):
        frag_file = "tmp/b.svg"
        main_file = "tmp/a.svg"
        main = svg()
        frag = svg()
        exp = svg()
        sb = ShapeBuilder()

        main.addElement(sb.createRect(0, 0, "200px", "100px"))
        exp.addElement(sb.createRect(0, 0, "200px", "100px"))

        frag.addElement(text("Hello World", x=210, y=110))
        exp.addElement(text("Hello World", x=210, y=110))
        main.save(main_file)
        frag.save(frag_file)
        append_svg_to_file(frag_file, main_file)

        svg_main = parse(main_file)
        gotS = str(svg_main.getXML())
        expS = str(exp.getXML())
        print "Got:", gotS
        print "Exp:", expS
        #self.assertEqual(exp.getXML(), svg_main.getXML(), "Appended files are equal" )
        if gotS != expS:
            print "Different\nGot:\n", gotS, "\nExp:\n", expS
Esempio n. 5
0
 def test_appending(self):
     frag_file="tmp/b.svg"
     main_file="tmp/a.svg"
     main = svg()
     frag = svg()
     exp = svg()
     sb = ShapeBuilder()
     
     main.addElement(sb.createRect(0, 0, "200px", "100px"))
     exp.addElement(sb.createRect(0, 0, "200px", "100px"))
     
     frag.addElement(text("Hello World", x = 210, y = 110))
     exp.addElement(text("Hello World", x = 210, y = 110))
     main.save(main_file)
     frag.save(frag_file)
     append_svg_to_file(frag_file,main_file)
     
     svg_main = parse(main_file)
     gotS =str(svg_main.getXML())
     expS = str(exp.getXML())
     print"Got:",gotS
     print"Exp:",expS
     #self.assertEqual(exp.getXML(), svg_main.getXML(), "Appended files are equal" )
     if gotS != expS :
         print "Different\nGot:\n",gotS,"\nExp:\n",expS
Esempio n. 6
0
def convert_dir( fill = None, dirname = '.', stroke = None, strokeWidth = None, dest = None):


    files = [ f for f in os.listdir(dirname) if f[-3:] == 'svg']
    print "{0} SVG Files: ".format(len(files))
    print '\n'.join(files)
                                 
    print "Converting fill to: {0}{1}{2}"\
        .format(fill,
                ", stroke to {0}".format(stroke) if stroke else '',
                ", strokeWidth to {0}".format(strokeWidth) if strokeWidth else '') 


    if dest == None:
        dest = ("{0}-fill{1}{2}"\
                .format(fill,
                        "-{0}-stroke".format(stroke) if stroke else '',
                        "-{0}-width".format(strokeWidth) if strokeWidth else '') )
    
    if not os.path.isdir(dest):
        os.mkdir(dest)

    for f in files:
        tree = svgparser.parse(os.path.join(dirname,f))
        elts = svgu.list_elements(tree)
        for e in elts:
            
            if 'set_fill' in dir(e) and fill:
                e.set_fill(fill)
            if 'set_stroke' in dir(e) and stroke:
                e.set_stroke(stroke)
            if 'set_stroke_width' in dir(e) and strokeWidth:
                e.set_stroke_width("{0}px".format(strokeWidth))
        out = os.path.join(dest, f)
        tree.save(out)
Esempio n. 7
0
 def import_svg(self,svg_file):
     try:
         svg_parsed = parse(svg_file)
         for e in svg_parsed.getAllElements():
             self.doc.addElement( e )
     except (ExpatError, IOError) as e:
         log.error("problem parsing %s:%s" % (svg_file,e))
         raise
Esempio n. 8
0
def leaf(x, y, width, dwg, id, rotate, args):
    leafsvg = parser.parse(args.dir + "leaf.svg")
    leaf = leafsvg.getElementAt(1)
    th = TransformBuilder()
    th.setScaling(width)
    th.setRotation(rotate)
    th.setTranslation("%d,%d" % (x, y))
    leaf.set_transform(th.getTransform())
    leaf.set_id(id)
    dwg.addElement(leaf)
Esempio n. 9
0
def leaf(x,y,width,dwg,id,rotate,args):
  leafsvg = parser.parse(args.dir + "leaf.svg")
  leaf = leafsvg.getElementAt(1)
  th=TransformBuilder()
  th.setScaling( width ) 
  th.setRotation( rotate)
  th.setTranslation( "%d,%d" % ( x ,y ) )
  leaf.set_transform(th.getTransform())
  leaf.set_id(id)
  dwg.addElement(leaf)
Esempio n. 10
0
 def make_icons(self, iconSRC, size, iconDest):
     original = parser.parse(iconSRC)
     #print  original.get_height()
     #print  original.get_width()
     fw = size / float(original.get_width())
     fh = size / float(original.get_height())
     original.set_width(size)
     original.set_height(size)
     original.set_transform("translate(0, 0) scale(" + str(fw) + "," +
                            str(fh) + ")")
     original.save(iconDest)
Esempio n. 11
0
def main():
    anSVG = parser.parse('./sourceimages/gtdsample.svg')
    print anSVG.getAllElements()
    for element in anSVG.getAllElements():
        if isinstance(element, TextContent)==False:
            print element.get_id()
    
    for element in anSVG.getAllElementsOfHirarchy():
         if isinstance(element, TextContent)==False:
            print element.get_id()
    
    for element in anSVG.getElementsByType(Rect):
        print element.get_id()
        print element.getAttributes()
Esempio n. 12
0
def main():
    anSVG = parser.parse('./sourceimages/gtdsample.svg')

    print anSVG.getAllElements()
    for element in anSVG.getAllElements():
        if isinstance(element, TextContent) == False:
            print element.get_id()

    for element in anSVG.getAllElementsOfHirarchy():
        if isinstance(element, TextContent) == False:
            print element.get_id()

    for element in anSVG.getElementsByType(Rect):
        print element.get_id()
        print element.getAttributes()
Esempio n. 13
0
    def parse_svg(svg_path):
        """
        Parses given SVG file
        :param svg_path: str
        :return: SVG object
        """

        if PSVG_AVAILABLE:
            try:
                svg_obj = parser.parse(svg_path)
            except Exception as exc:
                raise Exception('{} | SVG file "{}" is not valid!'.format(
                    exc, svg_path))
        else:
            raise Exception('PSV module dependency is not available!')

        return svg_obj
Esempio n. 14
0
    def transform_svg_for_robot(self, svg_file): 
        current_drawing = self.create_svg_doc(self.width,self.height)
        svg_data = parse(svg_file)

        #setup our transform
        tr = pysvg.builders.TransformBuilder()
        tr.setScaling(x=1,y=-1)
        trans = str(self.side_margin) + " " + str(self.img_height) 
        tr.setTranslation( trans )
        group = pysvg.structure.g()
        group.set_transform(tr.getTransform())
        #add the drawing
        for element in svg_data.getAllElements():
            group.addElement(element)

        current_drawing.addElement(group)
        return current_drawing
Esempio n. 15
0
    def transform_svg(self, svg_file, transform): 
        current_drawing = self.create_svg_doc()
        xoffset = transform.xoffset
        yoffset = transform.yoffset
        scale = transform.scale
        svg_data = parse(svg_file)

        #set up transform
        tr = pysvg.builders.TransformBuilder()
        tr.setScaling(scale)
        trans = str(xoffset) + " " + str(yoffset) 
        tr.setTranslation( trans )
        group = pysvg.structure.g()
        group.set_transform(tr.getTransform())

        for element in svg_data.getAllElements():
            group.addElement(element)

        current_drawing.addElement(group)
        return current_drawing
Esempio n. 16
0
def convert_dir(fill=None,
                dirname='.',
                stroke=None,
                strokeWidth=None,
                dest=None):

    files = [f for f in os.listdir(dirname) if f[-3:] == 'svg']
    print "{0} SVG Files: ".format(len(files))
    print '\n'.join(files)

    print "Converting fill to: {0}{1}{2}"\
        .format(fill,
                ", stroke to {0}".format(stroke) if stroke else '',
                ", strokeWidth to {0}".format(strokeWidth) if strokeWidth else '')

    if dest == None:
        dest = ("{0}-fill{1}{2}"\
                .format(fill,
                        "-{0}-stroke".format(stroke) if stroke else '',
                        "-{0}-width".format(strokeWidth) if strokeWidth else '') )

    if not os.path.isdir(dest):
        os.mkdir(dest)

    for f in files:
        tree = svgparser.parse(os.path.join(dirname, f))
        elts = svgu.list_elements(tree)
        for e in elts:

            if 'set_fill' in dir(e) and fill:
                e.set_fill(fill)
            if 'set_stroke' in dir(e) and stroke:
                e.set_stroke(stroke)
            if 'set_stroke_width' in dir(e) and strokeWidth:
                e.set_stroke_width("{0}px".format(strokeWidth))
        out = os.path.join(dest, f)
        tree.save(out)
Esempio n. 17
0
    except IOError as (errno, strerror):
        print "I/O error({0}): {1}".format(errno, strerror)


  if args.load:
    print "using numbers from file"
    loadedvars = pickle.load( open( args.dir + vars.p, "rb" ) )
    args.number = loadedvars["number"]
    args.env = loadedvars["env"]

  #create drawing
  dwg = setup(args)

  #also setup concat drawing
  try:
      concat = parser.parse(args.dir + "tree.svg")
      if args.debug:
        print "parsed concat ok"
  except:
      if args.debug:
        print "problem parsing concat"
      concat = setup(args)

  if args.wipe:
    write_date(concat)
    write_scale(concat)

  #draw outline square
  if args.drawoutline:
    dwg = setup(args)
    square( args.width / 2,args.height/2, args.width, dwg )
Esempio n. 18
0
def main():
    anSVG = parser.parse('./sourceimages/TMs10kSVGDemo.svg')
    anSVG.save('./testoutput/TMs10kSVGDemo.svg')
    
    anSVG = parser.parse('./sourceimages/clock.svg')
    anSVG.save('./testoutput/clock.svg')
Esempio n. 19
0
    else:
        fopen = open(table_path)
        table = dict([[e.strip() for e in re.split(re.compile('\s+'), l)]
                      for l in fopen.readlines()])

    ct = colors.color_names
    if ct.has_key(color):
        color = ct[color]
    for k, v in table.iteritems():
        if ct.has_key(k):
            table[ct[k]] = v
    for k, v in table.iteritems():
        if ct.has_key(v):
            table[k] = ct[v]

    svg_in = svgparser.parse(sys.stdin)

    elts = utils.list_elements(svg_in)
    if dofill:
        for e in elts:
            if not 'get_fill' in dir(e): continue
            if not colorall and not e.get_fill():
                continue

            if table.has_key(e.get_fill()):
                e.set_fill(table[e.get_fill()])
            else:
                e.set_fill(color)
    if dolines:
        for e in elts:
            if not 'get_color' in dir(e): continue
Esempio n. 20
0
    args = argparser.parse_args()
    state = {}
    loadedvars = {}

    if args.load:
        print "using numbers from file"
        loadedvars = pickle.load(open(args.dir + "vars.p", "rb"))
        args.number = loadedvars["number"]
        args.env = loadedvars["env"]

    #create drawing
    dwg = setup(args)

    #also setup concat drawing
    try:
        concat = parser.parse(args.dir + "concat.svg")
        stripsvg(concat)
        if args.debug:
            print "parsed concat ok"
    except IOError:
        if args.debug:
            print "problem parsing concat"
        concat = setup(args)

    #draw outline square
    if args.drawoutline:
        dwg = setup(args)
        square(args.width / 2, args.height / 2, args.width, dwg)
        dwg.save()
        exit(0)
Esempio n. 21
0
            fromfile.close()
        except IOError as (errno, strerror):
            print "I/O error({0}): {1}".format(errno, strerror)

    if args.load:
        print "using numbers from file"
        loadedvars = pickle.load(open(args.dir + vars.p, "rb"))
        args.number = loadedvars["number"]
        args.env = loadedvars["env"]

    #create drawing
    dwg = setup(args)

    #also setup concat drawing
    try:
        concat = parser.parse(args.dir + "tree.svg")
        if args.debug:
            print "parsed concat ok"
    except:
        if args.debug:
            print "problem parsing concat"
        concat = setup(args)

    if args.wipe:
        write_date(concat)
        write_scale(concat)

    #draw outline square
    if args.drawoutline:
        dwg = setup(args)
        square(args.width / 2, args.height / 2, args.width, dwg)
Esempio n. 22
0
def main():
    anSVG = parser.parse('./sourceimages/TMs10kSVGDemo.svg')
    anSVG.save('./testoutput/TMs10kSVGDemo.svg')

    anSVG = parser.parse('./sourceimages/clock.svg')
    anSVG.save('./testoutput/clock.svg')
Esempio n. 23
0
  state = {}
  loadedvars = {} 


  if args.load:
    print "using numbers from file"
    loadedvars = pickle.load( open( args.dir + "vars.p", "rb" ) )
    args.number = loadedvars["number"]
    args.env = loadedvars["env"]

  #create drawing
  dwg = setup(args)

  #also setup concat drawing
  try:
      concat = parser.parse(args.dir + "concat.svg")
      stripsvg(concat)
      if args.debug:
        print "parsed concat ok"
  except IOError:
      if args.debug:
        print "problem parsing concat"
      concat = setup(args)

  #draw outline square
  if args.drawoutline:
    dwg = setup(args)
    square( args.width / 2,args.height/2, args.width, dwg )
    dwg.save()
    exit(0)
Esempio n. 24
0
from pysvg.structure import *
from pysvg.core import *
from pysvg.text import *
from pysvg import parser

#anSVG = parser.parse('algo.svg')
anSVG = parser.parse('xx2.svg')
print anSVG.get_height()
print anSVG.get_width()

anSVG.set_width(120)
anSVG.set_height(120)
#print  anSVG.get_height()
#print  anSVG.get_width()

#anSVG.setAttribute("width","150px")

s = svg(width="200px", height="200px")
#s=svg()
s.addElement(anSVG)
print s.get_height()
print s.get_width()

s.save('zz.svg')
Esempio n. 25
0
        
    

    ct = colors.color_names
    if ct.has_key(color):
        color = ct[color]
    for k,v in table.iteritems():
        if ct.has_key(k):
            table[ct[k]] = v;
    for k,v in table.iteritems():
        if ct.has_key(v):
            table[k] = ct[v];

            
    
    svg_in = svgparser.parse(sys.stdin)
    
    elts = utils.list_elements(svg_in)
    if dofill:
        for e in elts:
            if not 'get_fill' in dir(e): continue;
            if not colorall and not e.get_fill():
                continue
            
            if table.has_key(e.get_fill()):
                e.set_fill(table[e.get_fill()])
            else:
                e.set_fill(color)
    if dolines:
        for e in elts:
            if not 'get_color' in dir(e): continue;
Esempio n. 26
0
 def load_svg(self,svg_file):
     svg_parsed = parse(svg_file)
     return svg_parsed
Esempio n. 27
0
def load_tutorial():
    s = parse('./testoutput/5_Line.svg')
    print(s.getXML())