def generate(self): tex_file = os.path.join(self.tempdir, 'input.tex') pdf_file = os.path.join(self.tempdir, 'input.pdf') # Auto-generate by pdflatex svg_file = os.path.join(self.tempdir, 'output.svg') with open(tex_file, 'w') as fhl: self.write_latex(fhl) call('pdflatex', tex_file,\ output_directory=self.tempdir,\ halt_on_error=True, oldie=True) inkscape(pdf_file, export_filename=svg_file, pdf_page=1, pdf_poppler=True, export_type="svg") if not os.path.isfile(svg_file): fn = os.path.basename(svg_file) if os.path.isfile(fn): # Inkscape bug detected, file got saved wrong svg_file = fn with open(svg_file, 'r') as fhl: svg = load_svg(fhl).getroot() svg.set_random_ids(backlinks=True) for child in svg: if isinstance(child, ShapeElement): yield child elif isinstance(child, Defs): for def_child in child: #def_child.set_random_id() self.svg.defs.append(def_child)
def effect(self): """Main entry point to process current document. Not to be called externally.""" actions_list = self.custom_effect(self) if actions_list is None or actions_list == []: self.msg( "No actions received. Perhaps you are calling inkex object methods?" ) elif isinstance(actions_list, list): tempfile = self.options.input_file + "-BaseExtension.svg" # prepare copy2(self.options.input_file, tempfile) actions_list.append("FileSave") actions_list.append("FileQuit") actions = ";".join(actions_list) inkscape(tempfile, "--with-gui", actions=actions) # finish up # replace current document with content of temp copy file self.document = inkex.load_svg(tempfile) # update self.svg self.svg = self.document.getroot() # Clean up tempfile try: os.remove(tempfile) except Exception: # pylint: disable=broad-except pass
def effect(self): self.is_installed() # Check version. base_view = self.svg.xpath("//sodipodi:namedview[@id='base']") if base_view is None: raise inkex.AbortExtension( _("Could not obtain the selected layer for inclusion of the video element." )) layer = self.svg.get_current_layer() if layer is None: raise inkex.AbortExtension( _("Could not obtain the selected layer for inclusion of the video element.\n\n" )) template = inkex.load_svg(self.get_resource('jessyink_video.svg')) root = template.getroot() elem = layer.add( root.getElement("//svg:g[@jessyink:element='core.video']").copy()) node_dict = find_internal_links(elem, root, {}) delete_ids(elem) for node in node_dict.values(): elem.insert(0, node) for node in node_dict.values(): node.set_id(self.svg.get_unique_id("jessyink.core.video"), backlinks=True)
def _load_glyphs(self): svg_path = os.path.join(self.path, "%s.svg" % self.variant) svg = inkex.load_svg(svg_path).getroot() svg = self._apply_transforms(svg) glyph_layers = svg.xpath(".//svg:g[starts-with(@inkscape:label, 'GlyphLayer-')]", namespaces=inkex.NSS) for layer in glyph_layers: self._clean_group(layer) layer.attrib[INKSCAPE_LABEL] = layer.attrib[INKSCAPE_LABEL].replace("GlyphLayer-", "", 1) glyph_name = layer.attrib[INKSCAPE_LABEL] self.glyphs[glyph_name] = Glyph(layer)
def load_path(filename): """Loads a super-path from a given SVG file""" base = os.path.normpath( os.path.join(os.getcwd(), os.path.dirname(__file__))) # __file__ is better then sys.argv[0] because this file may be a module # for another one. fullpath = os.path.join(base, filename) tree = load_svg(fullpath) root = tree.getroot() elem = root.findone('svg:path') if elem is None: return None, 0, 0 width = float(root.get("width")) height = float(root.get("height")) return elem.path.to_arrays( ), width, height # Currently we only support a single path
def loop_pathops(self, top_path, other_paths): """Loop through selected items and run external command(s).""" # init variables count = 0 max_ops = self.options.max_ops or 500 ink_verb = self.options.ink_verb or "SelectionDiff" dry_run = self.options.dry_run tempfile = self.options.input_file + "-pathops.svg" # prepare if dry_run: inkex.utils.debug("# Top object id: {}".format(top_path)) inkex.utils.debug("# Other objects total: {}".format( len(other_paths))) else: # we need to do this because command line Inkscape with gui # gives lots of info dialogs when the file extension isn't 'svg' # so the inkscape() call cannot open the file without user # interaction, and fails in the end when trying to save copy2(self.options.input_file, tempfile) # loop through sorted id list, process in chunks for chunk in chunks(other_paths, max_ops): count += 1 if dry_run: inkex.utils.debug("\n# Processing {}. chunk ".format(count) + "with {} objects ...".format(len(chunk))) self.run_pathops(tempfile, top_path, chunk, ink_verb, dry_run) # finish up if dry_run: inkex.utils.debug( "\n# {} chunks processed, ".format(count) + "with {} total objects.".format(len(other_paths))) else: # replace current document with content of temp copy file self.document = inkex.load_svg(tempfile) # update self.svg self.svg = self.document.getroot() # optionally delete top-most element when done if not self.options.keep_top: top_node = self.svg.getElementById(top_path) if top_node is not None: top_node.delete() # purge missing tagrefs (see below) self.update_tagrefs() # clean up self.cleanup(tempfile)
def run_document(self): """Run the actions on the svg xml tree""" if not self.has_action: return self.svg_document # First save the document svgfile = tempfile.mktemp(".svg") self.svg_document.write(svgfile) # Run the action on the document self.run_file(svgfile) # Open the resulting file with open(svgfile, 'r') as stream: self.svg_document = load_svg(stream) # Clean up. try: os.remove(svgfile) except Exception: pass # Return the new document return self.svg_document
def render_stitch_plan(svg, stitch_plan, realistic=False, visual_commands=True): layer = svg.find(".//*[@id='__inkstitch_stitch_plan__']") if layer is None: layer = inkex.Group( attrib={ 'id': '__inkstitch_stitch_plan__', INKSCAPE_LABEL: _('Stitch Plan'), INKSCAPE_GROUPMODE: 'layer' }) else: # delete old stitch plan del layer[:] # make sure the layer is visible layer.set('style', 'display:inline') svg.append(layer) for i, color_block in enumerate(stitch_plan): group = inkex.Group( attrib={ 'id': '__color_block_%d__' % i, INKSCAPE_LABEL: "color block %d" % (i + 1) }) layer.append(group) if realistic: color_block_to_realistic_stitches(color_block, svg, group) else: color_block_to_paths(color_block, svg, group, visual_commands) if realistic: filter_document = inkex.load_svg(realistic_filter) svg.defs.append(filter_document.getroot())
def get_template(cls): name = "seamless_pattern.svg" path = os.path.dirname(os.path.realpath(__file__)) return load_svg(os.path.join(path, name))
def effect(self): self.document = load_svg(inkscape_command( self.svg, verbs=['EditSelectAllInAllLayers', 'EditUnlinkClone', 'ObjectToPath'], ))
def symbols_svg(): with open(symbols_path()) as symbols_file: return inkex.load_svg(symbols_file).getroot()