def label_rect(fig, x, y, w, h, color="black", fill="none", name="", inside=False, text=True): top_offset = -3 bottom_offset = 13 if inside: top_offset = 13 bottom_offset = -3 fig.append([ rect(x, y, w, h, width=1, color=color, fill=fill), ]) if text: fig.append([ sg.TextElement(x, y + top_offset, f"{name}: ({x},{y})", size=12, weight="bold"), sg.TextElement(x + w, y + h + bottom_offset, f"({x+w},{y+h})", size=12, weight="bold", anchor="end"), ])
def main(args): fig = sg.SVGFigure("50cm", "50cm") fig1 = sg.fromfile(args.panel_one) fig2 = sg.fromfile(args.uc) fig3 = sg.fromfile(args.panel_two) fig4 = sg.fromfile(args.clinvar) fig5 = sg.fromfile(args.denovo) plot1 = fig1.getroot() plot2 = fig2.getroot() plot3 = fig3.getroot() plot4 = fig4.getroot() plot5 = fig5.getroot() plot1.moveto(0, 0, scale=0.75) plot2.moveto(0, 150, scale=0.75) plot3.moveto(0, 300, scale=0.75) plot4.moveto(0, 450, scale=0.75) plot5.moveto(0, 600, scale=0.75) # add text labels txt1 = sg.TextElement(25, 20, "panel one", size=12, weight="bold") txt2 = sg.TextElement(25, 150, "uc", size=12, weight="bold") txt3 = sg.TextElement(25, 300, "panel two", size=12, weight="bold") txt4 = sg.TextElement(25, 450, "clinvar", size=12, weight="bold") txt5 = sg.TextElement(25, 600, "denovo db", size=12, weight="bold") fig.append([plot1, plot2, plot3, plot4, plot5]) fig.append([txt1, txt2, txt3, txt4, txt5]) fig.save(args.out)
def make_a_chain(name: str, src_file: str, out_root="./"): fig = svgutils.transform.fromfile(src_file) root = fig.getroot() text_margin = 0.08 font_size = 13 font_family = "monospace" font_weight = "bold" name_text = sg.TextElement( x=cm_to_px(0.5 + text_margin), # coord is bottom left corner of text y=cm_to_px(0.5 + .5 - text_margin), text=name, size=font_size, font=font_family, weight=font_weight) year_text = sg.TextElement( x=WIDTH_UNITS - cm_to_px(0.5 + text_margin * 2), y=HEIGHT_UNITS - cm_to_px(0.5 + text_margin), text="2023", size=font_size, anchor="end", # "right justify" font=font_family, weight=font_weight) fig.append([root, name_text, year_text]) clean_name = name.strip().replace(" ", "") fig.save(os.path.join(out_root, f"{clean_name}_{src_file}"))
def plot_point_bar_figure(figure_one_path, figure_two_path): """ Combines the pointplot and bargraph together using svg magic Arguments: figure_one_path - The pointplot figure figure_two_path - The barplot figure """ fig = sg.SVGFigure("1280", "960") fig.append([ etree.Element("rect", { "width": "100%", "height": "100%", "fill": "white" }) ]) fig1 = sg.fromfile(figure_one_path) plot1 = fig1.getroot() plot1.moveto(22, 25, scale=1.35) fig2 = sg.fromfile(figure_two_path) plot2 = fig2.getroot() plot2.moveto(662, 0, scale=1.35) fig.append([plot1, plot2]) text_A = sg.TextElement(10, 30, "A", size=18, weight="bold") text_B = sg.TextElement(640, 30, "B", size=18, weight="bold") fig.append([text_A, text_B]) return fig
def main(args): fig = sg.SVGFigure("22cm", "25cm") fig1 = sg.fromfile(args.gene_counts) fig2 = sg.fromfile(args.mpc_dist) fig3 = sg.fromfile(args.fg_roc) fig4 = sg.fromfile(args.clinvar_roc) plot1 = fig1.getroot() plot2 = fig2.getroot() plot3 = fig3.getroot() plot4 = fig4.getroot() plot1.moveto(0, 20, scale=0.75) plot2.moveto(400, 0, scale=0.75) plot3.moveto(0, 390, scale=0.7) plot4.moveto(410, 390, scale=0.7) # add text labels txt1 = sg.TextElement(25, 20, "a", size=12, weight="bold") txt2 = sg.TextElement(400, 20, "b", size=12, weight="bold") txt3 = sg.TextElement(25, 390, "c", size=12, weight="bold") txt4 = sg.TextElement(400, 390, "d", size=12, weight="bold") fig.append([plot1, plot2, plot3, plot4]) fig.append([txt1, txt2, txt3, txt4]) fig.save(args.out)
def plot_cross_relationship(all_results, graph_loc, prediction_loc, size=4.6, dpi=300, ext='pdf', plot_dir=None): assert ext in ['pdf', 'svg'], 'Must use svg or pdf' tmp_dir = '/tmp/' plot_corr_heatmap(all_results, size=size / 3, plot_dir=tmp_dir, ext='svg') plot_glasso_edge_strength(all_results, graph_loc, size / 4, plot_dir=tmp_dir, ext='svg') plot_cross_within_prediction(prediction_loc, size / 4, plot_dir=tmp_dir, ext='svg') fig1 = sg.fromfile('/tmp/data_correlations.svg') fig2 = sg.fromfile('/tmp/cross_prediction.svg') fig3 = sg.fromfile('/tmp/glasso_edge_strength.svg') width = float(fig1.get_size()[0][:-2]) height = float(fig2.get_size()[1][:-2]) fig = sg.SVGFigure(width * 2.5, height) fig.root.set("viewbox", "0 0 %s %s" % (width * 2, height)) plot1 = fig1.getroot() plot2 = fig2.getroot() plot3 = fig3.getroot() # move plots plot2.moveto(width, 0) plot3.moveto(width * 1.8, 0) fig.append([plot1, plot2, plot3]) # add text txt1 = sg.TextElement(0, height * .1, "A", size=size * 1.5, weight="bold") txt2 = sg.TextElement(width * 1.05, height * .1, "B", size=size * 1.5, weight="bold") txt3 = sg.TextElement(width * 1.85, height * .1, "C", size=size * 1.5, weight="bold") fig.append([txt1, txt2, txt3]) # save svg_file = path.join(plot_dir, 'cross_relationship.svg') fig.save(svg_file) if ext == 'pdf': pdf_file = path.join(plot_dir, 'cross_relationship.pdf') a = subprocess.Popen('cairosvg %s -o %s' % (svg_file, pdf_file), shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) # remove temp files remove('/tmp/data_correlations.svg') remove('/tmp/glasso_edge_strength.svg') remove('/tmp/cross_prediction.svg')
def write(self): label = click.style('Cards Processed', fg='yellow') with click.progressbar(self.data, label=label, show_eta=True) as data: for card in data: self.layout = sg.fromfile(self.getLayout()) output_file = os.path.join(self.dir, '%05d.svg' % card['number']) numbers = [] for k in card['card'].keys(): numbers = numbers + card['card'][k] w, h = self.layout.get_size() c = sg.SVGFigure(w, h) c.append(self.layout) fillables = self.getFillables() for i in range(len(numbers)): fillable = fillables[i] number = numbers[i] txt = sg.TextElement( fillable['x'] + (fillable['width'] - Writer.FONT_SIZE * Writer.H_FACTOR) / 2, fillable['y'] + (fillable['height'] + Writer.FONT_SIZE * Writer.V_FACTOR) / 2, "%02d" % number, size=Writer.FONT_SIZE, weight="bold", font="Helvetica") c.append(txt) c.save(output_file) print click.style('\nCards written to %s' % self.dir, fg='blue') + '\n'
def put_list_of_figs_to_svg_fig(FIGS, CAP_SIZE=14,\ fig_name="fig.svg", visualize=True,\ transparent=True): """ take a list of figures and make a """ label = list(string.ascii_uppercase)[:len(FIGS)] fig = sg.SVGFigure("21cm", "29.7cm") # A4 figure PLOT_LIST, LABEL_LIST = [], [] for i in range(len(FIGS)): ff = 'f.svg' FIGS[i].savefig(ff, format='svg', transparent=transparent) fig1 = sg.fromfile(ff) plot = fig1.getroot() plot.moveto(10. * i, 10. * i, scale=1.) PLOT_LIST.append(plot) txt = sg.TextElement(10.*i, 10.*i, label[i%26],\ size=CAP_SIZE, weight="bold") LABEL_LIST.append(txt) fig.append(PLOT_LIST) fig.append(LABEL_LIST) fig.save(fig_name) if visualize: os.system('eog ' + fig_name) os.system('rm f.svg')
def combine_figs(*labeled_figs, unit="px"): """Combines the given figures horizontally.""" # Assumes all figures have the same height and use the same size units plots = [] labels = [] cur_offset = 0 for fig, label in labeled_figs: plot = fig.getroot() plot.moveto(cur_offset, 0) plots.append(plot) width = int(fig.width.strip(unit)) left_label_offset = 0.0125 * width top_label_offset = 0.0375 * width font_size = 0.03 * width text = sg.TextElement(left_label_offset + cur_offset, top_label_offset, label, size=font_size) labels.append(text) cur_offset += width height = labeled_figs[0][0].height combined_fig = sg.SVGFigure(cur_offset, height) combined_fig.append(plots) combined_fig.append(labels) return combined_fig
def _gen_grid(self, dx, dy, width=0.5): xmax, ymax = 1000, 1000 x, y = 0, 0 lines = [] txt = [] while x < xmax: lines.append(_transform.LineElement([(x, 0), (x, ymax)], width=width)) txt.append(_transform.TextElement(x, dy/2, str(x), size=self.size)) x += dx while y < ymax: lines.append(_transform.LineElement([(0, y), (xmax, y)], width=width)) txt.append(_transform.TextElement(0, y, str(y), size=self.size)) y += dy return lines+txt
def plot_point_bar_figure(figure_one_path, figure_two_path): """ Combines the pointplot and bargraph together using svg magic Arguments: figure_one_path - The pointplot figure figure_two_path - The barplot figure """ fig1 = sg.fromfile(figure_one_path) fig2 = sg.fromfile(figure_two_path) fig1_width_size = np.round(float(fig1.root.attrib["width"][:-2]) * 1.33, 0) fig1_height_size = np.round( float(fig1.root.attrib["height"][:-2]) * 1.33, 0) fig2_width_size = np.round(float(fig2.root.attrib["width"][:-2]) * 1.33, 0) fig2_height_size = np.round( float(fig2.root.attrib["height"][:-2]) * 1.33, 0) fig = sg.SVGFigure( Unit((fig1_width_size + fig2_width_size) - 360), Unit(min(fig1_height_size, fig2_height_size) - 50), ) fig.append([ etree.Element("rect", { "width": "100%", "height": "100%", "fill": "white" }) ]) plot1 = fig1.getroot() plot1.moveto(10, 30) plot2 = fig2.getroot() plot2.moveto(fig1_width_size - 160, 12) text_A = sg.TextElement(10, 30, "A", size=18, weight="bold") text_B = sg.TextElement(fig1_width_size - 160, 30, "B", size=18, weight="bold") fig.append([plot1, plot2, text_A, text_B]) return fig
def __init__(self, text, x=None, y=None, **kwargs): params = {'size': CONFIG['text.size'], 'weight': CONFIG['text.weight'], 'font': CONFIG['text.font']} if x is None or y is None: x, y = CONFIG['text.position'] params.update(kwargs) element = _transform.TextElement(x, y, text, **params) Element.__init__(self, element.root)
def letter_annotations(svgs): """Add letters based on the location of the images.""" return [ sg.TextElement(svg.x + 10, svg.y + 15, letter_annotation, size=15, weight="bold") for letter_annotation, svg in svgs.items() ]
def __init__(self, text, x=None, y=None, **kwargs): params = { "size": CONFIG["text.size"], "weight": CONFIG["text.weight"], "font": CONFIG["text.font"], } if x is None or y is None: x, y = CONFIG["text.position"] params.update(kwargs) element = _transform.TextElement(x, y, text, **params) Element.__init__(self, element.root)
def north_arrow(img_file_in: Path, img_file_out: Path = None, rotation_angle=0): if img_file_out is None: img_file_out = img_file_in.parent / f"{img_file_in.name[:-4]}_north_arrow.svg" arrow_fig_path = Path(__file__).parent.parent / "north_arrow.svg" # load matpotlib-generated figures fig1 = sg.fromfile(str(img_file_in)) fig2 = sg.fromfile(str(arrow_fig_path)) #create new SVG figure fig = sg.SVGFigure(fig1.get_size()) w, h = get_fig_size(fig1) # get the plot objects plot1 = fig1.getroot() plot2 = fig2.getroot() print(fig2.get_size()) x_label = 0.9 * w y_label = 0.8 * h kx = 0.5 * 0.05 ky = 0.05 plot2.scale_xy(x=kx, y=ky) w_fig2, h_fig2 = get_fig_size(fig2) plot2.moveto(x_label - w_fig2 * kx / 2, y_label) print(fig2.get_size()) n_text = sg.TextElement(0.9 * w, 0.8 * h, "N", size=12, weight="bold", anchor="middle") fig.append([plot1, plot2]) fig.append([ n_text, ]) fig.set_size(fig1.get_size()) fig.save(str(img_file_out))
def el(char, path, x, y, scale=1, offset=(10, 30)): toret = [] if char is not None: toret.append(RectElement(x + offset[0], y + offset[1])) toret.append( sg.TextElement(x + offset[0], y + offset[1], char, size=24, weight='bold', font='Arial')) if path.endswith(".svg"): svg = sg.fromfile(path) svg = svg.getroot() svg.moveto(str(x), str(y), scale) return [svg] + toret
def makeSVG(output,sc=0.435,W2=680/2 ,H1=300): #create new SVG figure fig = sg.SVGFigure("19.05cm", "22.86cm") # load matpotlib-generated figures figA2 = sg.fromfile(output+os.sep+'FigureB_histXY.svg') figA1= sg.fromfile(output+os.sep+'FigureA_histXY.svg') figB4 = sg.fromfile(output+os.sep+'angle_hist.svg') figB=[] for n in [u'ext__Bacteria_Rad25_1_3', u'ext__IngredientC_1_1', u'ext__snake']: fig2 = sg.fromfile(output+os.sep+n+"_histXY_labels.svg") figB.append(fig2) figB.append(figB4) # W2 = 680/2 # H1 = 350 # get the plot objects plot1 = figA1.getroot() plot1.moveto(5, 0, scale=sc) plot2 = figA2.getroot() plot2.moveto(W2, 0, scale=sc) plot3 = figB[0].getroot() plot3.moveto(5, H1, scale=sc) plot4 = figB[1].getroot() plot4.moveto(W2, H1, scale=sc) plot5 = figB[2].getroot() plot5.moveto(5, H1*2, scale=sc) plot6 = figB[3].getroot() plot6.moveto(W2, H1*2, scale=sc) # add text labels txt1 = sg.TextElement(25,20, "A.1", size=12, weight="bold") txt2 = sg.TextElement(W2+5,20, "A.2", size=12, weight="bold") txt3 = sg.TextElement(25,20+H1, "B.1", size=12, weight="bold") txt4 = sg.TextElement(W2+5,20+H1, "B.2", size=12, weight="bold") txt5 = sg.TextElement(25,20+H1*2, "B.3", size=12, weight="bold") txt6 = sg.TextElement(W2+5,20+H1*2, "B.4", size=12, weight="bold") # append plots and labels to figure fig.append([plot1, plot2]) fig.append([plot3, plot4]) fig.append([plot5, plot6]) fig.append([txt1, txt2]) fig.append([txt3, txt4]) fig.append([txt5, txt6]) # save generated SVG files fig.save(output+os.sep+"fig_final.svg")
def generate_figures(self, fname, highlight=None): _image_len = self.width / self.row self.__subimages = [(s, moldraw(s, size=(_image_len, _image_len), highlight_atoms=highlight)) for s in self.__smiles] _fig = sg.SVGFigure(str(self.width), str(self.height)) _subfigs = [ sg.fromfile(ff[1]) for ff in self.__subimages if ff[1] is not None ] _labels = range(len(_subfigs)) _plots = [ff.getroot() for ff in _subfigs] _x_coord = 0 _y_coord = 0 _final_coords = [] for sf in _plots: if _x_coord + (self.width % self.row) == self.width: _x_coord = 0 _y_coord += 1.25 * _image_len sf.moveto(_x_coord, _y_coord, scale=1.0) _final_coords.append((_x_coord, _y_coord)) _x_coord += _image_len else: sf.moveto(_x_coord, _y_coord, scale=1.0) _final_coords.append((_x_coord, _y_coord)) _x_coord += _image_len _txt = [ sg.TextElement(loc[0] + _image_len / 2, loc[1] + 1.1 * _image_len, str(n + 1), size=36, weight='bold', font='Arial') for loc, n in zip(_final_coords, _labels) ] _fig.append(_plots) _fig.append(_txt) _fig.save(fname)
def el(char, path, x, y, w=None, h=None, scale=1, offset=(0, 0)): svg, textel = [], [] if char is not None: textel = [ sg.TextElement(x + offset[0] + 0.5, y + offset[1] + 11, char, size=14, weight='bold', font='Arial') ] if path is not None: svg = sg.fromfile(path) if w is not None and h is not None: svg.set_size((w, h)) svg = svg.getroot() svg.moveto(str(x), str(y), scale) svg = [svg] return svg + textel
def compose_svg_figure(figure_spec, filename, size, display=False): """Compose a figure from multiple SVG components. Parameters ---------- figure_spec : dict Structure describing subfigures to compose (see below). filename : str File name to save composed SVG size : tuple Size of final SVG document like ("16cm", "10cm") display : bool If True, display the complete SVG in Jupyter notebook. Each item in *figure_spec* is a dict containing:: { 'figure': <matplotlib Figure>, 'pos': (x, y), 'scale': 1.0, 'label': 'A', 'label_opts': {'size': 16, 'weight': 'bold'}, } """ import svgutils.transform as svg fig = svg.SVGFigure(*size) for item in figure_spec: subfig = svg.from_mpl(item['figure'], savefig_kw={'bbox_inches':'tight', 'pad_inches':0}) root = subfig.getroot() root.moveto(item['pos'][0], item['pos'][1], scale=item.get('scale', 1.0)) label = svg.TextElement(item['pos'][0], item['pos'][1], item['label'], **item.get('label_opts', {})) fig.append([root, label]) fig.save(filename) if display: from IPython.display import SVG, display display(SVG(filename=filename))
import svgutils.transform as sg import sys #create new SVG figure fig = sg.SVGFigure("16cm", "6.5cm") # load matpotlib-generated figures fig1 = sg.fromfile('sigmoid_fit.svg') fig2 = sg.fromfile('anscombe.svg') # get the plot objects plot1 = fig1.getroot() plot2 = fig2.getroot() plot2.moveto(280, 0, scale=0.5) # add text labels txt1 = sg.TextElement(25,20, "A", size=12, weight="bold") txt2 = sg.TextElement(305,20, "B", size=12, weight="bold") # append plots and labels to figure fig.append([plot1, plot2]) fig.append([txt1, txt2]) # save generated SVG files fig.save("fig_final.svg")
scale_x_input=0.9, scale_y_input=0.9, x_loc=30, y_loc=900, ) panel_1dright = make_figure_panel( os.path.join(local_directory, "simulated_volcano_DEG_SRP061689.svg"), scale_x_input=0.95, scale_y_input=0.95, x_loc=400, y_loc=885, ) panel_1a_label = sg.TextElement(10, 20, "A", size=18, weight="bold", font="Verdana") panel_1b_label = sg.TextElement(900, 20, "B", size=18, weight="bold", font="Verdana") panel_1c_label = sg.TextElement(10, 300, "C", size=18, weight="bold", font="Verdana") panel_1d_label = sg.TextElement(10,
def plot_scatter_clouds( scatter_plot_path, word_cloud_x_path, word_cloud_y_path, final_figure_path="output/pca_plots/figures/final_figure.png"): # Save the matplotlfigures scatter_plot = Path(scatter_plot_path) scatter_plot_output = f"output/pca_plots/svg_files/{scatter_plot.stem}.svg" word_cloud_x = Path(word_cloud_x_path) word_cloud_x_output = f"output/pca_plots/svg_files/{word_cloud_x.stem}.svg" word_cloud_y = Path(word_cloud_y_path) word_cloud_y_output = f"output/pca_plots/svg_files/{word_cloud_y.stem}.svg" save_plot(str(scatter_plot), scatter_plot_output) save_plot(str(word_cloud_x), word_cloud_x_output) save_plot(str(word_cloud_y), word_cloud_y_output) #create new SVG figure fig = sg.SVGFigure("1280", "768") # load matpotlib-generated figures fig1 = sg.fromfile(word_cloud_y_output) fig2 = sg.fromfile(scatter_plot_output) fig3 = sg.fromfile(word_cloud_x_output) # get the plot objects plot1 = fig1.getroot() plot1.moveto(-40, -20, scale=0.98) plot2 = fig2.getroot() plot2.moveto(420, -110, scale=1.4) plot3 = fig3.getroot() plot3.moveto(460, 370, scale=0.98) # append plots and labels to figure fig.append([plot2, plot1, plot3]) text_A = sg.TextElement(10, 30, "A", size=20, weight="bold") text_B = sg.TextElement(510, 30, "B", size=20, weight="bold") text_C = sg.TextElement(510, 390, "C", size=20, weight="bold") fig.append([text_A, text_B, text_C]) second_pc = int(re.search(r"pca_(\d+)", word_cloud_y.stem).group(1)) first_pc = int(re.search(r"pca_(\d+)", word_cloud_x.stem).group(1)) word_cloud_title_1 = sg.TextElement(200, 370, f"pca{second_pc}", size=22, weight="bold") word_cloud_title_2 = sg.TextElement(713, 760, f"pca{first_pc}", size=22, weight="bold") fig.append([word_cloud_title_1, word_cloud_title_2]) # save generated SVG files svg2png(bytestring=fig.to_str(), write_to=final_figure_path, dpi=500) return Image(final_figure_path)
import numpy as np import os import os.path try: figs = [] for i in range(2): figs.append(plt.figure()) plt.plot(np.random.random(100)) layout = VerticalLayout() sz = map(int, sg.from_mpl(figs[0]).get_size()) sz[1] *= 3 sz = map(str, sz) layout.set_size(sz) layout.add_figure(sg.from_mpl(figs[0])) layout.add_figure(sg.from_mpl(figs[1])) txt1 = sg.TextElement(50, 50, "HELLO", size=12) layout.append([txt1]) layout.save(os.path.join('/', 'tmp', 'stack_plots.svg')) try: print('converting to pdf') subprocess.call( '/Applications/Inkscape.app/Contents/Resources/bin/inkscape --export-pdf=/tmp/stack_plots.pdf /tmp/stack_plots.svg', shell=True) except: print('unable to run inkscape') finally: plt.close('all')
#!/usr/bin/env python3 # coding=utf-8 from svgutils import transform fig = transform.SVGFigure("100px", "40px") txt1 = transform.TextElement("0", "10", "ABCDEFGHIJ", size=12) txt2 = transform.TextElement("0", "20", "ABCDEFGHIJ", size=12, letterspacing=1) txt3 = transform.TextElement("0", "30", "ABCDEFGHIJ", size=12, letterspacing=2) txt4 = transform.TextElement("0", "40", "ABCDEFGHIJ", size=12, letterspacing=-1) fig.append([txt1, txt2, txt3, txt4]) fig.save("letterspacing.svg")
panel_five_size = ( np.round(float(panel_five.root.attrib["width"][:-2]) * 1.33, 0), np.round(float(panel_five.root.attrib["height"][:-2]) * 1.33, 0), ) scale_x = 1.4 scale_y = 1.4 print(f"original: {panel_five_size}") print(f"scaled:{(panel_five_size[0]*scale_x, panel_five_size[1]*scale_y)}") panel_five = panel_five.getroot() panel_five.scale(x=scale_x, y=scale_y) panel_five.moveto(1070, 1670) # - panel_one_label = sg.TextElement(30, 30, "A", size=30, weight="bold") panel_two_label = sg.TextElement(10, 800, "B", size=30, weight="bold") panel_three_label = sg.TextElement(1100, 800, "C", size=30, weight="bold") panel_four_label = sg.TextElement(30, 1670, "D", size=30, weight="bold") panel_five_label = sg.TextElement(1100, 1670, "E", size=30, weight="bold") # + figure_one = sg.SVGFigure(Unit(2127), Unit(2433)) figure_one.append([ etree.Element("rect", { "width": "100%", "height": "100%", "fill": "white" }), panel_one,
# Author: Gregory Ewing # Contact: [email protected] # Date: January 2019 # Description: Combine svg layers base, latest, and recommended into a single svg # file base_latest_recommended.svg' import svgutils.transform as sg import subprocess import datetime as dt ## DIFFERENT SCRIPT IN FINAL final = sg.SVGFigure("19in", "11.5in") base = sg.fromfile('GRAPHICS/base_v2.svg') base = base.getroot() latest = sg.fromfile('GRAPHICS/latest.svg') latest = latest.getroot() recs = sg.fromfile('GRAPHICS/recommended.svg') recs = recs.getroot() t_str = "Dash Build Time: " + dt.datetime.utcnow().strftime( "%m-%d %H:%M") + " UTC" build_time = sg.TextElement(25, 60, t_str, size=12, color='red') final.append([base, latest, recs, build_time]) final.set_size(["1900px", "1150px"]) final.save('GRAPHICS/base_latest_recommended.svg')
def create_label_page(ids, page_num): global x, y label_sheet = sg.SVGFigure('612', '792') # 8.5"x11" paper at 72dpi labels = [] # Convert the base label pdf to svg pdf2svg(label_pdf, 'output/label.svg') for nodeid in ids: nodeidstr = nodeid.replace(':', '') if QR_IN_USE: # Create the QR code img = qrcode.make(QR_CODE_STR.format(nodeid), image_factory=qrcode.image.svg.SvgPathImage, box_size=7, version=4, border=0) img.save('output/qr_{}.svg'.format(nodeidstr)) # Color the QR code with open('output/qr_{}.svg'.format(nodeidstr), 'r+') as f: svg = f.read() f.seek(0) svg = svg.replace('fill:#000000;', 'fill:{};'.format(QR_COLOR)) f.write(svg) # Create the node specific svg fig = sg.SVGFigure('{}px'.format(label_pixels_x), '{}px'.format(label_pixels_y)) rawlabel = sg.fromfile('output/label.svg') rawlabelr = rawlabel.getroot() if QR_IN_USE: qr = sg.fromfile('output/qr_{}.svg'.format(nodeidstr)) qrr = qr.getroot() # position correctly (hand tweaked) qrr.moveto(label_qr_pos_x, label_qr_pos_y, label_qr_scale) # position modifications based on text (x_mod, y_mod, nodeid) = position_label(nodeid) #txt = sg.TextElement(100,318, nodeid, size=28, font='Courier') txt = sg.TextElement(label_id_pos_x + x_mod, label_id_pos_y + y_mod, nodeid, size=label_id_font, font='Droid Sans', letterspacing=label_id_letterspacing, anchor='middle') if QR_IN_USE: fig.append([rawlabelr, qrr, txt]) else: fig.append([rawlabelr, txt]) fig.save('output/label_{}.svg'.format(nodeidstr)) if label_rotate: fig = sg.SVGFigure('{}px'.format(label_pixels_y), '{}px'.format(label_pixels_x)) dlabel = sg.fromfile('output/label_{}.svg'.format(nodeidstr)) dlabelr = dlabel.getroot() dlabelr.rotate(90, x=0, y=0) dlabelr.moveto(0, -1 * label_pixels_y) fig.append([dlabelr]) fig.save('output/label_{}.svg'.format(nodeidstr)) # labels.append(fig) # Convert the id specific image to pdf # sh.rsvg_convert('-f', 'pdf', '-o', 'label_{}.pdf'.format(nodeidstr), # 'label_{}.svg'.format(nodeidstr)) # Stamp the label with id specific image # pdftk(CASE_LABEL, 'stamp', 'unique_{}.pdf'.format(nodeidstr), 'output', # 'label_{}.pdf'.format(nodeidstr)) # pdf2svg('label_{}.pdf'.format(nodeidstr), 'label_{}.svg'.format(nodeidstr)) lbl = sg.fromfile('output/label_{}.svg'.format(nodeidstr)) lblr = lbl.getroot() pos = get_coordinates() lblr.moveto(pos[0], pos[1], 1) # position correctly (hand tweaked) if pos[2]: labels.append(lblr) label_sheet.append(labels) label_sheet.save('output/all_labels_{}.svg'.format(page_num)) sh.rsvg_convert('-f', 'pdf', '-d', '72', '-p', '72', '-o', 'output/all_labels_{}.pdf'.format(page_num), 'output/all_labels_{}.svg'.format(page_num)) # cleanup after yourself x = POSITION_START_X y = POSITION_START_Y for fl in glob.glob('output/label_*'): os.remove(fl)
np.round(float(panel_five.root.attrib['width'][:-2]) * 1.33, 0), np.round(float(panel_five.root.attrib['height'][:-2]) * 1.33, 0), ) scale_x = 1.15 scale_y = 1.15 print(f"original: {panel_five_size}") print(f"scaled:{(panel_five_size[0]*scale_x, panel_five_size[1]*scale_y)}") panel_five = panel_five.getroot() panel_five.scale_xy(x=scale_x, y=scale_y) panel_five.moveto(620, 1000, scale=1) # In[8]: panel_one_label = sg.TextElement(10, 20, "A", size=22, weight="bold") panel_two_label = sg.TextElement(10, 600, "B", size=22, weight="bold") panel_three_label = sg.TextElement(610, 600, "C", size=22, weight="bold") panel_four_label = sg.TextElement(30, 1010, "D", size=22, weight="bold") panel_five_label = sg.TextElement(620, 1010, "E", size=22, weight="bold") # In[9]: figure_one = sg.SVGFigure("1600", "1400") figure_one.append([ etree.Element("rect", { "width": "100%", "height": "100%", "fill": "white" }), panel_one, panel_two, panel_three, panel_four, panel_five, panel_one_label, panel_two_label, panel_three_label, panel_four_label,
rawlabel = sg.fromfile(label_svg) rawlabelr = rawlabel.getroot() qr = sg.fromfile('qr_{}.svg'.format(nodeidstr)) qrr = qr.getroot() # position correctly (hand tweaked) qrr.moveto(label_qr_pos_x, label_qr_pos_y, label_qr_scale) if label_txt_func: nodeid_txt = label_txt_func(nodeid) else: nodeid_txt = nodeid txt = sg.TextElement(label_id_pos_x, label_id_pos_y, nodeid_txt, size=label_id_font, font='Courier', letterspacing=label_id_letterspacing) if ltype == 'gecko': fig.append([rawlabelr, txt]) else: fig.append([rawlabelr, qrr, txt]) fig.save('label_{}.svg'.format(nodeidstr)) if label_rotate: fig = sg.SVGFigure('{}px'.format(label_pixels_y), '{}px'.format(label_pixels_x)) dlabel = sg.fromfile('label_{}.svg'.format(nodeidstr)) dlabelr = dlabel.getroot() dlabelr.rotate(90, x=0, y=0) dlabelr.moveto(0, -1*label_pixels_y) fig.append([dlabelr])