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 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 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 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 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 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 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 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