def vector(self, e): scale = float(e.get('scale', '1.0')) width = toLength(e.get('width')) height = toLength(e.get('height')) path = e.get('src') search = e.get('search', None) replace = e.get('replace', None) fh = open(self.get_from_url(path), 'rb') data = fh.read() fh.close() if search is not None: data = data.replace(search, replace) svg = xml.dom.minidom.parseString(data).documentElement svgRenderer = SvgRenderer() svgRenderer.render(svg) svg_obj = svgRenderer.finish() svg_obj.scale(scale, scale) svg_obj.asDrawing(width, height) yield svg_obj
def vector(self, e): scale = float(e.get('scale', '1.0')) width = toLength(e.get('width')) height = toLength(e.get('height')) path = e.get('src') search = e.get('search', None) replace = e.get('replace', None) fh = open(self.media_root + path, 'rb') data = fh.read() fh.close() if search is not None: data = data.replace(search, replace) import xml.dom.minidom svg = xml.dom.minidom.parseString(data).documentElement from svglib.svglib import SvgRenderer svgRenderer = SvgRenderer() svgRenderer.render(svg) svg_obj = svgRenderer.finish() svg_obj.scale(scale, scale) svg_obj.asDrawing(width, height) yield svg_obj
def svg_to_pdf(svg_data): svgr = SvgRenderer() doc = minidom.parseString(svg_data.encode("utf-8")) svgr.render(doc.documentElement) drawing = svgr.finish() pdf = renderPDF.drawToString(drawing) return pdf
def post(self, request, *args, **kwargs): data = request.POST.get('svgdata', '') doc = xml.dom.minidom.parseString(data.encode( "utf-8" )) svg = doc.documentElement svgRenderer = SvgRenderer() svgRenderer.render(svg) drawing = svgRenderer.finish() pdf = renderPDF.drawToString(drawing) response = HttpResponse(content_type='application/pdf') response["Content-Disposition"]= "attachment; filename=chart.pdf" response.write(pdf) return response
def altair_to_pdf(chart, filename, webdriver='firefox'): from lxml import etree from svglib.svglib import SvgRenderer from reportlab.graphics import renderPDF import tempfile import os name = tempfile.mktemp() with open(name, 'w') as fp: chart.save(fp, format='svg', webdriver=webdriver) parser = etree.XMLParser( remove_comments=True, resolve_entities=True) doc = etree.parse(name, parser=parser) svg_root = doc.getroot() svgRenderer = SvgRenderer(name) drawing = svgRenderer.render(svg_root) if drawing is not None: data = renderPDF.drawToString(drawing) with open(filename, 'wb') as output: output.write(data) os.remove(name)
def do2(self, fig=None, **kwargs): from lxml import etree from reportlab.graphics import renderPM from svglib.svglib import SvgRenderer w, h, s = self.width, self.height, self.scale svg = fig.to_image(format="svg", width=w, height=h, scale=s * self.upscale) root = etree.fromstring(svg.decode("utf-8")) if root is None: raise Exception("Error while converting Plotly graphic.") svgRenderer = SvgRenderer("my.svg") drawing = svgRenderer.render(root) buf = io.BytesIO() renderPM.drawToFile(drawing, buf, fmt="PNG") buf.seek(0) _bytes = np.asarray(bytearray(buf.read()), dtype=np.uint8) img = cv2.imdecode(_bytes, cv2.IMREAD_COLOR) _w = int((int(root.get("width")) / self.upscale)) _h = int((int(root.get("height")) / self.upscale)) img = cv2.resize(img, (_w, _h), interpolation=cv2.INTER_AREA) return img
def create_formation_image(names_list, cache_dir, GK_name=None): """ Create soccer formation image using names of attending players. """ with open_text("cktool", "formation.svg") as f: svg_data = f.read() svg_data = svg_data.replace("_z_", str(len(names_list))) if GK_name and GK_name in names_list: svg_data = svg_data.replace(f"_GK_", GK_name) names_list.remove(GK_name) for i, _ in enumerate(names_list.copy(), start=1): svg_data = svg_data.replace(f"_x{i}_", names_list.pop()) for i in range(1, 30): svg_data = svg_data.replace(f"_x{i}_", "?") svg_root = etree.fromstring(svg_data, parser=etree.XMLParser(remove_comments=True, recover=True)) svgRenderer = SvgRenderer(path="") drawing = svgRenderer.render(svg_root) filename = "formation_{}.png".format( dt.datetime.now().strftime("%Y%m%d_%Hh%Mm%Ss")) filepath = os.path.join(cache_dir, filename) renderPM.drawToFile(drawing, filepath, fmt="PNG") return filepath
def export_svg(request): # Получаем данные с клиентской части использую переменные POST svg = request.POST.get("svg") doc = xml.dom.minidom.parseString(svg.encode( "utf-8" )) svg = doc.documentElement # Создаём новый экземпляр класса SvgRenderer svgRenderer = SvgRenderer() svgRenderer.render(svg) drawing = svgRenderer.finish() # Вместо записы исходного файла на диск мы позволяем пользователю сразу скачать его pdf = renderPDF.drawToString(drawing) response = HttpResponse(mimetype='application/pdf') response.write(pdf) # Реализуем возможность просмотра полученного pda файла прямо в браузерном плагине response["Content-Disposition"]= "attachment; filename=converted.pdf" return response
def export_svg(request): # Получаем данные с клиентской части использую переменные POST svg = request.POST.get("svg") doc = xml.dom.minidom.parseString(svg.encode("utf-8")) svg = doc.documentElement # Создаём новый экземпляр класса SvgRenderer svgRenderer = SvgRenderer() svgRenderer.render(svg) drawing = svgRenderer.finish() # Вместо записы исходного файла на диск мы позволяем пользователю сразу скачать его pdf = renderPDF.drawToString(drawing) response = HttpResponse(mimetype='application/pdf') response.write(pdf) # Реализуем возможность просмотра полученного pda файла прямо в браузерном плагине response["Content-Disposition"] = "attachment; filename=converted.pdf" return response
def export_svg(request): svg = request.POST.get("svg_xml") title = request.POST.get("title") format = request.POST.get("format") if format == "svg": # Set mimetype to octet-stream to assure download from browser response = HttpResponse(svg, mimetype="application/octet-stream") elif format == "pdf": doc = xml.dom.minidom.parseString(svg.encode( "utf-8" )) svg = doc.documentElement svgRenderer = SvgRenderer() svgRenderer.render(svg) drawing = svgRenderer.finish() pdf = renderPDF.drawToString(drawing) response = HttpResponse(mimetype='application/pdf') response.write(pdf) # Need to change with actual title response["Content-Disposition"]= "attachment; filename=%s.%s" % (title, format) return response
def render_png(self, width=800, height=800): # svglib expects an lxml structure internally parser = etree.XMLParser(remove_comments=True, recover=True) svg = etree.fromstring(self.get_xml().encode("utf-8"), parser=parser) # render the SVG to a PNG renderer = SvgRenderer(None) drawing = renderer.render(svg) scale_x = width / drawing.width scale_y = height / drawing.height drawing.width = width drawing.height = height drawing.scale(scale_x, scale_y) return renderPM.drawToString(drawing, fmt="PNG")
def export_save(request): svg = request.POST.get("svg_xml") title = request.POST.get("title") format = request.POST.get("format") country = request.POST.get("country") year = request.POST.get("year") viz = request.POST.get("viz") # import os directory = "exports/%s" % viz if not os.path.exists(directory): os.makedirs(directory) directory = "exports/%s/%s" % (viz, country) if not os.path.exists(directory): os.makedirs(directory) file_name = '/%s.%s' % (title, format) file_name = directory + file_name if format == "svg": # Set mimetype to octet-stream to assure download from browser svg = svg.encode( "utf-8" ) f = open(file_name, 'w') f.write(svg) elif format == "pdf": doc = xml.dom.minidom.parseString(svg.encode( "utf-8" )) svg = doc.documentElement svgRenderer = SvgRenderer() svgRenderer.render(svg) drawing = svgRenderer.finish() renderPDF.drawToFile(drawing, file_name) # # pdf = renderPDF.drawToString(drawing) # # response = HttpResponse(mimetype='application/pdf') # response.write(pdf) # Need to change with actual title return HttpResponse(title)
def fromstring(xml_string, replacements=None, **kwargs): """create svg graphics from string""" if replacements: for (key, value) in replacements.items(): xml_string = xml_string.replace(("{%s}" % key).encode(), value.encode()) parser = etree.XMLParser(remove_comments=True, recover=True) svg = etree.fromstring(xml_string, parser=parser) # convert to a RLG drawing svg_renderer = SvgRenderer("", **kwargs) drawing = svg_renderer.render(svg) return drawing
def vector(self, e): scale = float(e.get('scale', '1.0')) width = toLength(e.get('width')) height = toLength(e.get('height')) path = e.get('src') search = e.get('search', None) replace = e.get('replace', None) with open(self.get_from_url(path), 'rb') as fh: data = fh.read() if search is not None: data = data.replace(search, replace) svg = etree.fromstring(data) renderer = SvgRenderer() drawing = renderer.render(svg) drawing.scale(scale, scale) drawing.asDrawing(width, height) yield drawing
def parse_parts(self, buffer): # prepare ReportLab self.styles = getSampleStyleSheet() self.style_stack.append(self.styles['Normal']) if self.out_buffer is None: self.out_buffer = StringIO() self.parts = [] # prepare for parsing i = 0 buffer_len = len(buffer) # Possible modes: 0 = normal, 1 = table row, 2 = insert object mode = 0 new_line = True new_para = True cue = 0 content = '' raw_table_data = '' self.reset_table() obj = None style_stack = self.style_stack paragraphs = split_ignore(buffer, '\n\n', '[[[block', ']]]') for p in paragraphs: lines = p.split('\n') content = '' for line in lines: c = line[:1] if c == '#': debug_print('[comment]') elif c == '$': self.parse_paragraph_style(line[1:]) elif c == '~': debug_print('[document element %s]' % line[1]) elem = line[1] endpos = line.find(']', 2) if elem == 'D': self.handle_document_properties(line[3:endpos], line[endpos+1:]) elif elem == 'T': if line[2] == '$': # table style raw_style = line[3:] style = self.parse_table_style(raw_style) self.table_styles.append(style) else: self.table_cols = list(float(n) * self.unit for n in line[3:endpos].split('|')) align = line[endpos+1:endpos+2] if align == '<': self.table_align = 'LEFT' elif align == '>': self.table_align = 'RIGHT' elif elem == 'B': self.append_to_parts(PageBreak()) elif elem == 'S': self.append_to_parts(Spacer(1, toLength(line[2:]))) elif elem == 'V': svg_info_raw = line[3:endpos] svg_info = svg_info_raw.split(';')[:7] if len(svg_info) == 1: mode = 2 obj = self.svg_dict[svg_info[0]] else: if len(svg_info) == 7: svg_name, svg_scale, svg_w, svg_h, svg_path, svg_find, svg_replace = svg_info else: svg_name, svg_scale, svg_w, svg_h, svg_path = svg_info svg_file = open(find(svg_path), 'rb') svg_data = svg_file.read() svg_file.close() if len(svg_info) == 7: svg_data = svg_data.replace(svg_find, svg_replace) svg = xml.dom.minidom.parseString(svg_data).documentElement svgRenderer = SvgRenderer() svgRenderer.render(svg) svg_obj = svgRenderer.finish() #svg_obj = svg2rlg(settings.MEDIA_ROOT + svg_path) svg_obj.scale(float(svg_scale), float(svg_scale)) svg_obj.asDrawing(float(svg_w) * self.unit, float(svg_h) * self.unit) self.svg_dict[svg_name] = svg_obj elif elem == 'I': img_info_raw = line[3:endpos] img_info = img_info_raw.split(';')[:4] if len(img_info) == 1: mode = 2 obj = self.img_dict[img_info[0]] else: img_name, img_w, img_h, img_path = img_info img_obj = Image(find(img_path), width=self.unit*float(img_w), height=self.unit*float(img_h)) align = line[endpos+1:endpos+2] if align == '<': img_obj.hAlign = 'LEFT' elif align == '>': img_obj.hAlign = 'RIGHT' self.img_dict[img_name] = img_obj elif elem == 'C': barcode_info_raw = line[3:endpos] barcode_info = barcode_info_raw.split(';')[:6] if len(barcode_info) == 1: mode = 2 obj = self.img_dict[barcode_info[0]] else: barcode_name, barcode_type, barcode_scale, barcode_w, barcode_h, barcode_data = barcode_info barcode_obj = Barcode(library=find('common/pdf_img/barcode.ps'), width=self.unit * float(barcode_w), height=self.unit * float(barcode_h), data=barcode_data, scale=float(barcode_scale), type=barcode_type) align = line[endpos+1:endpos+2] if align == '<': barcode_obj.hAlign = 'LEFT' elif align == '>': barcode_obj.hAlign = 'RIGHT' self.img_dict[barcode_name] = barcode_obj elif elem == 'F': font_info_raw = line[3:endpos] font_info = font_info_raw.split(';')[:2] self.import_pdf_font(font_info[1], font_info[0]) elif elem == 'P': if '[' in line: self.parts_buffer = line[3:endpos] self.parts_buffer_dict[self.parts_buffer] = [] else: self.parts_buffer = None elif c == '[': mode = 1 raw_table_data += line + '\n' elif c == '\n': pass else: if mode == 0: content += line + '\n' elif mode == 1: raw_table_data += line + '\n' if mode == 0: if content != '': self.append_to_parts(Paragraph(content, self.style_stack[-1] if len(self.style_stack) > 0 else self.styles['Normal'])) content = '' if mode == 1: td = raw_table_data td_len = len(td) i = 0 while i < td_len: c = td[i] c_1 = td[i-1:i] if c == '[' and c_1 != '\\': cue = i + 1 if (c == '|' or c == ']') and c_1 != '\\': cell_content = td[cue:i] pop_after_cell = False if cell_content[:1] == '$': if ' ' in cell_content: style, cell_content = cell_content.split(None, 1) style = style[1:] else: style = '' cell_content = cell_content[1:] self.parse_paragraph_style(style) if cell_content[-1:] == '$': cell_content = cell_content[:-1] pop_after_cell = True if cell_content[:2] == '~V': svg_name = cell_content[2:] self.table_row.append(self.svg_dict[svg_name]) elif cell_content[:2] == '~I': img_name = cell_content[2:] self.table_row.append(self.img_dict[img_name]) elif cell_content[:2] == '~P': self.table_row.append(self.parts_buffer_dict[cell_content[2:]]) else: self.table_row.append(Paragraph(cell_content, self.style_stack[-1] if len(self.style_stack) > 0 else self.styles['Normal'])) if pop_after_cell: self.parse_paragraph_style('') cue = i + 1 if c == ']': self.table_data.append(self.table_row) self.table_row = [] i += 1 if len(self.table_data) > 0: self.append_to_parts(Table(self.table_data, self.table_cols, hAlign=self.table_align, style=self.table_styles)) self.reset_table() raw_table_data = '' if mode == 2: if obj is not None: self.append_to_parts(obj) obj = None mode = 0 return self.parts
def write_to_pdf(dwg: Drawing, path: str): svg_str = dwg.tostring() svg = ET.fromstring(svg_str, etree.XMLParser()) svgRenderer = SvgRenderer(None) drawing = svgRenderer.render(svg) renderPDF.drawToFile(drawing, path)
def parse_parts(self, buffer): # prepare ReportLab self.styles = getSampleStyleSheet() self.style_stack.append(self.styles['Normal']) if self.out_buffer is None: self.out_buffer = StringIO() self.parts = [] # prepare for parsing i = 0 buffer_len = len(buffer) # Possible modes: 0 = normal, 1 = table row, 2 = insert object mode = 0 new_line = True new_para = True cue = 0 content = '' raw_table_data = '' self.reset_table() obj = None style_stack = self.style_stack paragraphs = split_ignore(buffer, '\n\n', '[[[block', ']]]') for p in paragraphs: lines = p.split('\n') content = '' for line in lines: c = line[:1] if c == '#': debug_print('[comment]') elif c == '$': self.parse_paragraph_style(line[1:]) elif c == '~': debug_print('[document element %s]' % line[1]) elem = line[1] endpos = line.find(']', 2) if elem == 'D': self.handle_document_properties( line[3:endpos], line[endpos + 1:]) elif elem == 'T': if line[2] == '$': # table style raw_style = line[3:] style = self.parse_table_style(raw_style) self.table_styles.append(style) else: self.table_cols = list( float(n) * self.unit for n in line[3:endpos].split('|')) align = line[endpos + 1:endpos + 2] if align == '<': self.table_align = 'LEFT' elif align == '>': self.table_align = 'RIGHT' elif elem == 'B': self.append_to_parts(PageBreak()) elif elem == 'S': self.append_to_parts(Spacer(1, toLength(line[2:]))) elif elem == 'V': svg_info_raw = line[3:endpos] svg_info = svg_info_raw.split(';')[:7] if len(svg_info) == 1: mode = 2 obj = self.svg_dict[svg_info[0]] else: if len(svg_info) == 7: svg_name, svg_scale, svg_w, svg_h, svg_path, svg_find, svg_replace = svg_info else: svg_name, svg_scale, svg_w, svg_h, svg_path = svg_info svg_file = open(find(svg_path), 'rb') svg_data = svg_file.read() svg_file.close() if len(svg_info) == 7: svg_data = svg_data.replace( svg_find, svg_replace) svg = xml.dom.minidom.parseString( svg_data).documentElement svgRenderer = SvgRenderer() svgRenderer.render(svg) svg_obj = svgRenderer.finish() # svg_obj = svg2rlg(settings.MEDIA_ROOT + svg_path) svg_obj.scale(float(svg_scale), float(svg_scale)) svg_obj.asDrawing( float(svg_w) * self.unit, float(svg_h) * self.unit) self.svg_dict[svg_name] = svg_obj elif elem == 'I': img_info_raw = line[3:endpos] img_info = img_info_raw.split(';')[:4] if len(img_info) == 1: mode = 2 obj = self.img_dict[img_info[0]] else: img_name, img_w, img_h, img_path = img_info img_obj = Image(find(img_path), width=self.unit * float(img_w), height=self.unit * float(img_h)) align = line[endpos + 1:endpos + 2] if align == '<': img_obj.hAlign = 'LEFT' elif align == '>': img_obj.hAlign = 'RIGHT' self.img_dict[img_name] = img_obj elif elem == 'C': barcode_info_raw = line[3:endpos] barcode_info = barcode_info_raw.split(';')[:6] if len(barcode_info) == 1: mode = 2 obj = self.img_dict[barcode_info[0]] else: barcode_name, barcode_type, barcode_scale, barcode_w, barcode_h, barcode_data = barcode_info barcode_obj = Barcode( library=find('common/pdf_img/barcode.ps'), width=self.unit * float(barcode_w), height=self.unit * float(barcode_h), data=barcode_data, scale=float(barcode_scale), type=barcode_type) align = line[endpos + 1:endpos + 2] if align == '<': barcode_obj.hAlign = 'LEFT' elif align == '>': barcode_obj.hAlign = 'RIGHT' self.img_dict[barcode_name] = barcode_obj elif elem == 'F': font_info_raw = line[3:endpos] font_info = font_info_raw.split(';')[:2] self.import_pdf_font(font_info[1], font_info[0]) elif elem == 'P': if '[' in line: self.parts_buffer = line[3:endpos] self.parts_buffer_dict[self.parts_buffer] = [] else: self.parts_buffer = None elif elem == 'E': args = line[2:].split(';') name, width, height, value = args self.append_to_parts( TextField(name, int(width), int(height), value)) elif c == '[': mode = 1 raw_table_data += line + '\n' elif c == '\n': pass else: if mode == 0: content += line + '\n' elif mode == 1: raw_table_data += line + '\n' if mode == 0: if content != '': self.append_to_parts( Paragraph( content, self.style_stack[-1] if len(self.style_stack) > 0 else self.styles['Normal'])) content = '' if mode == 1: td = raw_table_data td_len = len(td) i = 0 while i < td_len: c = td[i] c_1 = td[i - 1:i] if c == '[' and c_1 != '\\': cue = i + 1 if (c == '|' or c == ']') and c_1 != '\\': cell_content = td[cue:i] pop_after_cell = False if cell_content[:1] == '$': if ' ' in cell_content: style, cell_content = cell_content.split( None, 1) style = style[1:] else: style = '' cell_content = cell_content[1:] self.parse_paragraph_style(style) if cell_content[-1:] == '$': cell_content = cell_content[:-1] pop_after_cell = True if cell_content[:2] == '~V': svg_name = cell_content[2:] self.table_row.append(self.svg_dict[svg_name]) elif cell_content[:2] == '~I': img_name = cell_content[2:] self.table_row.append(self.img_dict[img_name]) elif cell_content[:2] == '~P': self.table_row.append( self.parts_buffer_dict[cell_content[2:]]) else: self.table_row.append( Paragraph( cell_content, self.style_stack[-1] if len(self.style_stack) > 0 else self.styles['Normal'])) if pop_after_cell: self.parse_paragraph_style('') cue = i + 1 if c == ']': self.table_data.append(self.table_row) self.table_row = [] i += 1 if len(self.table_data) > 0: self.append_to_parts( Table(self.table_data, self.table_cols, hAlign=self.table_align, style=self.table_styles)) self.reset_table() raw_table_data = '' if mode == 2: if obj is not None: self.append_to_parts(obj) obj = None mode = 0 return self.parts
def SVG2drawing(xml_data): doc = etree.fromstring(xml_data) svgRenderer = SvgRenderer() drawing = svgRenderer.render(doc) return drawing