def generate(self): parts = [] avg = json.loads(self.request.form['averages']) pSVG = self.request.form.get('pSVG') tf = tempfile.NamedTemporaryFile() tf.write(unicode(pSVG).encode('utf-8')) tf.seek(0) drawing = svg2rlg(tf.name) drawing.height = 350.0 pSVG1 = self.request.form.get('pSVG1') tf = tempfile.NamedTemporaryFile() tf.write(unicode(pSVG1).encode('utf-8')) tf.seek(0) drawing1 = svg2rlg(tf.name) ## Page1 self.frontpage(parts) ## Page2 parts.append(drawing) parts.append(Paragraph(LEGEND, styles['Normal'])) parts.append(PageBreak()) parts.append(Paragraph(u'Mittelwerte', styles['Normal'])) table = Table(data=avg) ts = TableStyle([ ('INNERGRID', (0, 0), (-1, -1), 0.25, colors.black), ('BOX', (0, 0), (-1, -1), 0.25, colors.black), ]) table.setStyle(ts) parts.append(table) parts.append(PageBreak()) parts.append(Spacer(0, 1*cm)) parts.append(drawing1) return parts
def test_use(self): drawing = svglib.svg2rlg(io.StringIO(textwrap.dedent(u'''\ <?xml version="1.0"?> <svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="10cm" height="3cm" viewBox="0 0 100 30"> <defs> <rect id="MyRect" width="60" height="10"/> </defs> <rect x=".1" y=".1" width="99.8" height="29.8" fill="none" stroke="blue" stroke-width=".2" /> <use x="20" y="10" xlink:href="#MyRect" /> <use x="30" y="20" xlink:href="#MyRect" fill="#f00" /> </svg> '''))) main_group = drawing.contents[0] # First Rect assert isinstance(main_group.contents[0], Rect) # Second Rect defined by the use node (inside a Group) assert isinstance(main_group.contents[1].contents[0], Rect) assert main_group.contents[1].contents[0].fillColor == colors.black # default # Attributes on the use node are applied to the referenced content assert isinstance(main_group.contents[2].contents[0], Rect) assert main_group.contents[2].contents[0].fillColor == colors.red
def create_preamble(name, style, logo): if ".svg" in logo: #check if the logo is in svg format tempf = open(logo, 'r') #open the file for reading s = tempf.read() height_k = re.search('height=\"(\d*).(\d*)', s) #get the height of the picture, using regular expressions height_l = float(re.search('\"(\d*).(\d*)', height_k.group(0)).group(0)[1:]) #get only the height width_k = re.search('width=\"(\d*).(\d*)', s) #get the width of the picture, using regular expressions width_l = float(re.search('\"(\d*).(\d*)', width_k.group(0)).group(0)[1:]) #get only the width drawing = svg2rlg(logo) #draw the picture logo = logo.replace(".svg", ".pdf") #replace the .svg part with .pdf renderPDF.drawToFile(drawing, "temp/" + logo[logo.rfind("/") + 1:]) #draw the picture to the file and render it else: width_l, height_l = Image.open(logo).size if(os.path.isfile(logo)): shutil.copy(logo, "temp/" + logo[logo.rfind("/") + 1:]) logo = logo[logo.rfind("/") + 1:] scale_height = 622.519685 / height_l scale_width = 418.110236 / width_l scale = (min(scale_height, scale_width)) #calculate how much the logo can be scaled f = open("Resources/SongBookletTemplate.tex", 'r', encoding = 'utf-8') #now create the tex file for the songbook itself tex = f.read() f.close() return tex.replace("***NAME***", name).replace("***LOGO***", logo).replace("***NUMBERING***", style).replace("***SCALE***", str(scale * 0.4))
def main(): c = canvas.Canvas('MyFirstLine.pdf', pagesize=letter) width, height = letter c.setFont('Helvetica', 12) c.drawCentredString(280, 770, 'First Line of Twinkle Twinkle Little Star') staff = Staff() # TODO: constants, enum different types of clefs & positions staff.applyClef(svg2rlg('./Images/GClef.svg')) getLinePos = staff.getNotePos m1 = Measure(4, getLinePos) n = Note(-1) m1.addNote(n) m1.addNote(Note(-1)) m2 = Measure(4, getLinePos) m2.addNote(Note(3)) m2.addNote(Note(3)) m2.addNote(Note(4)) m2.addNote(Note(4)) m3 = Measure(4, getLinePos) m3.addNote(Note(3)) m3.addNote(Note(3)) m3.addNote(Note(2)) m3.addNote(Note(2)) staff.addMeasure(m1) staff.addMeasure(m2) staff.addMeasure(m3) #staff.addMeasure(Measure(4)) staff.render(c, 50, 600) c.save()
def __init__(self, name, symbol, value, rgbcolor, offset): self.name = name self.value = value self.rgbcolor = rgbcolor self.offset = offset if symbol: self.symbol = svg2rlg("icons/%s.svg" % symbol) self.symbol.scale(.18, .18) else: self.symbol = None
def test_space_preservation(self): drawing = svglib.svg2rlg(io.StringIO(textwrap.dedent(u'''\ <?xml version="1.0"?> <svg width="777" height="267"> <text style="fill:#000000; stroke:none; font-size:28;"> <tspan>TITLE 1</tspan> <tspan x="-10.761" y="33.487">Subtitle</tspan> </text> </svg> '''))) main_group = drawing.contents[0] # By default, only two tspans produce String objects, the rest # (spaces/newlines) is ignored. assert len(main_group.contents[0].contents) == 2 assert main_group.contents[0].contents[0].text == "TITLE 1" drawing = svglib.svg2rlg(io.StringIO(textwrap.dedent(u'''\ <?xml version="1.0"?> <svg width="777" height="267" xml:space="preserve"> <text style="fill:#000000; stroke:none; font-size:28;"> <tspan>TITLE 1</tspan> <tspan x="-10.761" y="33.487">Subtitle</tspan> </text> </svg> '''))) main_group = drawing.contents[0] assert main_group.contents[0].contents[0].text == ' ' assert main_group.contents[0].contents[1].text == "TITLE 1" drawing = svglib.svg2rlg(io.StringIO(textwrap.dedent(u'''\ <?xml version="1.0"?> <svg width="777" height="267"> <text style="fill:#000000; stroke:none; font-size:28;"> <tspan>TITLE 1</tspan> <tspan x="-10.761" y="33.487">Subtitle</tspan> </text> <text xml:space="preserve"> with spaces </text> </svg> '''))) main_group = drawing.contents[0] # xml:space can be overriden per text node assert main_group.contents[0].contents[0].text == "TITLE 1" assert main_group.contents[1].contents[0].text == ' with spaces '
def _draw_front(self, canvas): canvas.saveState() # Draw red border self._draw_single_border(canvas, 0, self.width, self.height) # Parchment background self._draw_single_background( canvas, 0, self.border_front, self.width, self.height, self.front_orientation, ) # Set card orientation if self.front_orientation == Orientation.TURN90: canvas.rotate(90) canvas.translate(0, -self.width) width = self.height height = self.width else: width = self.width height = self.height # D&D logo dnd_logo = svg2rlg(ASSET_DIR / "logo.svg") if dnd_logo is not None: factor = self.LOGO_WIDTH / dnd_logo.width dnd_logo.width *= factor dnd_logo.height *= factor dnd_logo.scale(factor, factor) logo_margin = (self.border_front[Border.TOP] - self.bleed - dnd_logo.height) / 2 renderPDF.draw( dnd_logo, canvas, (width - self.LOGO_WIDTH) / 2, height - self.border_front[Border.TOP] + logo_margin, ) self._draw_front_frame(canvas, width, height) # Artist if self.artist: canvas.setFillColor("white") artist_font_height = self.fonts.set_font(canvas, "artist") canvas.drawCentredString( width / 2, self.border_front[Border.BOTTOM] - artist_font_height - 1 * mm, "Artist: {}".format(self.artist), ) canvas.restoreState()
def extract_stroke_from_graphics_file(char_path, svg_path, save_path): if not os.path.exists(save_path): os.mkdir(save_path) # load json data from graphics.txt chars = [] with open(char_path, "r") as f: for ch in f.readlines(): chars.append(ch.strip()) svg_names = [f for f in os.listdir(svg_path) if ".svg" in f] if len(svg_names) == 0: print("svg is none") return for i in range(len(chars)): ch = chars[i] code = ch.encode("unicode_escape").decode("utf-8").replace("\\u", "").upper() svg_name = "" for sn in svg_names: if ch in sn: svg_name = sn break if svg_name == "": print("{} not find svg file".format(ch)) continue dom = minidom.parse(os.path.join(svg_path, svg_name)) root = dom.documentElement path_elems = root.getElementsByTagName("path") if path_elems is None or len(path_elems) == 0: print("{} svg not find path".format(ch)) continue new_dom, path_parent_elem = create_blank_svg(copy.deepcopy(dom)) for p_id in range(len(path_elems)): path_parent_elem.appendChild(path_elems[p_id]) data_xml = new_dom.toxml() svg_p = os.path.join(save_path, "{}_{}_{}.svg".format(ch, code, p_id)) with open(svg_p, "w") as f: f.write(data_xml) # save to png drawing = svg2rlg(svg_p) if drawing is None: print("drawing is None!") png_p = os.path.join(save_path, "{}_{}_{}.png".format(ch, code, p_id)) renderPM.drawToFile(drawing, png_p, "png") img = cv2.imread(png_p, 0) img = cv2.resize(img, (256, 256)) cv2.imwrite(png_p, img) os.remove(svg_p)
def test_no_fill_on_shape(self): """ Any shape with no fill property should set black color in rlg syntax. """ drawing = svglib.svg2rlg(io.StringIO( '''<?xml version="1.0" encoding="UTF-8"?> <svg xmlns="http://www.w3.org/2000/svg" width="1200" height="800" viewBox="0 0 36 24"> <rect y="10" width="36" height="4"/> </svg>''' )) self.assertEqual(drawing.contents[0].contents[0].fillColor, colors.black)
def svg2png(file_path): try: drawing = svg2rlg(file_path) new_file_path = file_path[:-3] + "png" renderPM.drawToFile(drawing, new_file_path, fmt="PNG") if file_path is not None: os.system("rm " + file_path + " &") return new_file_path except: if file_path is not None: os.system("rm " + file_path + " &")
def makepdf(self, path, name, x, y, z, q): from svglib.svglib import svg2rlg from reportlab.pdfgen import canvas from reportlab.graphics import renderPDF rlg = svg2rlg(path) rlg.scale(0.8, 0.8) c = canvas.Canvas(name) c.setPageSize((x, y)) renderPDF.draw(rlg, c, z, q) c.showPage() c.save()
def svg2pdf(infile, outfile=""): if outfile == "": out = os.path.splitext(infile)[0] + ".pdf" else: out = outfile # if os.path.isabs(out): # out_abs = out # else: # out_abs = os.path.join(os.getcwd(), out) drawing = svg2rlg(infile) renderPDF.drawToFile(drawing, out)
def fen_to_image(fen): board = chess.Board(fen) current_board = chess.svg.board(board=board) output_file = open('current_board.svg', "w") output_file.write(current_board) output_file.close() svg = svg2rlg('current_board.svg') renderPM.drawToFile(svg, 'current_board.png', fmt="PNG") return board
def save_file(path, image, name_file): log.info(f'4/4 Saving image: {name_file}') with open(name_file + '.svg', 'w') as f: f.write('<?xml version=\"1.0\" standalone=\"no\"?>\n') f.write('<!DOCTYPE svg PUBLIC \"-//W3C//DTD SVG 1.1//EN\"\n') f.write('\"http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd\">\n') f.write(tostring(image, encoding="unicode")) drawing = svg2rlg(name_file + '.svg') renderPDF.drawToFile(drawing, name_file + '.pdf') return True
def test_filehandle_input(self): try: with NamedTemporaryFile(mode='w', suffix='.svg', delete=False) as fp: fp.write(self.test_content) file_path = fp.name with open(file_path, 'rb') as fp: drawing = svglib.svg2rlg(fp) assert drawing is not None finally: os.unlink(file_path)
def test_no_width_height(self): drawing = svglib.svg2rlg(io.StringIO(textwrap.dedent('''\ <?xml version="1.0"?> <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 480 360"> <g fill="#E70013"> <rect x="60" y="40" width="120" height="80"/> </g> </svg> '''))) assert (drawing.width, drawing.height) == (480, 360)
def get_thumbnail(url): filename, _ext = os.path.splitext(os.path.basename(url)) img_path = os.path.sep.join( [THUMBNAILS_DIRECTORY, "{}.png".format(filename)]) svg_path = os.path.sep.join( [THUMBNAILS_DIRECTORY, "{}.svg".format(filename)]) # This thumbnail gets converted with an error, so download it separately for now if "US_history" in filename: return files.ThumbnailFile(path="US_history.png") # Copy pngs to local storage if url.endswith("png"): with open(img_path, 'wb') as pngobj: pngobj.write(downloader.read(url)) elif url.endswith("svg"): with open(svg_path, 'wb') as svgobj: # renderPM doesn't read <style> tags, so add style to individual elements svg_contents = BeautifulSoup(downloader.read(url), 'html.parser') svg_contents = BeautifulSoup( svg_contents.find('svg').prettify(), 'html.parser') if svg_contents.find('style'): sheet = cssutils.parseString(svg_contents.find('style').string) for rule in sheet: rectangles = svg_contents.find_all( 'rect', {'class': rule.selectorText.lstrip('.')}) paths = svg_contents.find_all( 'path', {'class': rule.selectorText.lstrip('.')}) polygons = svg_contents.find_all( 'polygon', {'class': rule.selectorText.lstrip('.')}) for el in rectangles + paths + polygons: el['style'] = "" for prop in rule.style: el['style'] += "{}:{};".format( prop.name, prop.value) # Beautifulsoup autocorrects some words to be all lowercase, so undo correction autocorrected_fields = ["baseProfile", "viewBox"] svg = svg_contents.find('svg') for field in autocorrected_fields: if svg.get(field.lower()): svg[field] = svg[field.lower()] del svg[field.lower()] svgobj.write(svg_contents.renderContents()) drawing = svg2rlg(svg_path) renderPM.drawToFile(drawing, img_path) else: import pdb pdb.set_trace() return files.ThumbnailFile(path=img_path)
def save_barcode_image(sender, instance, **kwargs): barcode_dir = os.path.join(settings.MEDIA_DIR, 'barcode') bar_code_name = instance.barcode EAN = barcode.get_barcode_class('code39') ean = EAN(bar_code_name) fullname = ean.save(os.path.join(barcode_dir, bar_code_name)) file = open(f'{os.path.join(barcode_dir,bar_code_name)}.svg', 'rb') drawing = svg2rlg(file) pdf_file = renderPDF.drawToFile( drawing, f'{os.path.join(barcode_dir,bar_code_name)}.pdf') instance.barcode_image = 'barcode/' + f'{bar_code_name}.pdf'
def get_image_story(impath, imw=80, imh=60, title=None, style=None): out_story = [FrameBreak()] img = svg2rlg(impath) scaling_factor = imw*mm/img.width img.width = imw*mm img.height = imh*mm img.scale(scaling_factor, scaling_factor) out_story.append(img) if title and style: out_story.append(Paragraph("<font color='#95C11E' name=Arial-bold>{}</font>".format(title), style)) return out_story
def gen_png_from_svg(self): """ A function used to first generate a SVG image of the chess board. After this the SVG image will be converted to a PNG image. """ board_svg = chess.svg.board(board=self.board) output_file = open('board.svg', "w") output_file.write(board_svg) output_file.close() drawing = svg2rlg("board.svg") renderPM.drawToFile(drawing, "board.png", fmt="PNG")
def country_flag(country): if not os.path.exists('tmp'): os.makedirs('tmp') country_code = COUNTRY_CODES.get(country.title()) flag_remote = rapi.get_country_by_country_code(COUNTRY_CODES.get(country.title())).flag flag_local_svg = 'tmp/{}.svg'.format(country_code) flag_local_png = 'tmp/{}.png'.format(country_code) urllib.request.urlretrieve(flag_remote, flag_local_svg) renderPM.drawToFile(svg2rlg(flag_local_svg), flag_local_png, fmt='PNG') flag_pil = Image.open(flag_local_png) return flag_pil
def compose_bs_by_bs_name(bs_dict_str, type="jianti"): svg_names = [f for f in os.listdir(svg_imgs_path) if ".svg" in f] jianti_list = bs_dict_str.split("|") print(len(jianti_list)) for jt_item in jianti_list: bs_name = jt_item.split(":")[0] svg_char = jt_item.split(":")[1] sk_orders = jt_item.split(":")[-1].split(" ") sk_orders = [int(s) for s in sk_orders] print(bs_name) svg_file = "" for sn in svg_names: if svg_char in sn: svg_file = sn break if svg_file == "": continue svg_path = os.path.join(svg_imgs_path, svg_file) # open svg file dom = minidom.parse(svg_path) # find path element in original svg file root = dom.documentElement path_elems = root.getElementsByTagName("path") if path_elems is None: print("not find path elements") return print("path elements len: ", len(path_elems)) dom_, path_parent_elem = create_blank_svg(copy.deepcopy(dom)) for id in sk_orders: path_parent_elem.appendChild(path_elems[id]) data_xml = dom_.toxml() with open("./{}_temp/{}.svg".format(type, bs_name), 'w') as f: f.write(data_xml) drawing = svg2rlg("./{}_temp/{}.svg".format(type, bs_name)) if drawing is None: print("drawing is None!") renderPM.drawToFile(drawing, "./{}_temp/{}.png".format(type, bs_name), "png") os.system("rm {}".format("./{}_temp/{}.svg".format(type, bs_name)))
def svg_save(): img_data = request.form.get("imgData") print("svg size", len(img_data)) with open("temp.svg", "w", encoding="utf-8") as tout: tout.write(img_data) drawing = svg2rlg("temp.svg") renderPM.drawToFile(drawing, "temp.png", fmt="PNG") return json.dumps({"success": True, "msg": ""})
def svg_to_png(svg_file, output_file): """ Method to convert an SVG file to a PNG file. This method requires the third-party library svglib. """ # uses svglib to render a SVG to PDF from svglib.svglib import svg2rlg from reportlab.graphics import renderPM drawing = svg2rlg(svg_file) renderPM.drawToFile(drawing, output_file, fmt='PNG')
def save(self, extension='svg'): upper_extension = extension.upper() #test if there is a .svg if len(self.path.split('.svg')) != 2: raise ValueError( 'You need to add the .svg in the path file with the pathname method' ) elif self.path.split('.svg')[1] != '': raise ValueError( 'You need to add the .svg in the path file with the pathname method' ) if os.path.isfile(self.path): existing = True else: existing = False self.dwg.save() if upper_extension == 'SVG': return elif upper_extension in ['PNG', 'BMP', 'PPM', 'JPG', 'JPEG', 'GIF']: from svglib.svglib import svg2rlg from reportlab.graphics import renderPDF, renderPM convertedurl = self.path.split('.svg')[0] + '.' + extension drawing = svg2rlg(self.path) renderPM.drawToFile(drawing, convertedurl, fmt=upper_extension) elif upper_extension in ['PDF']: from svglib.svglib import svg2rlg from reportlab.graphics import renderPDF convertedurl = self.path.split('.svg')[0] + '.' + extension drawing = svg2rlg(self.path) renderPDF.drawToFile(drawing, convertedurl) else: raise ValueError('Unknown Format {}'.format(extension)) if not existing and upper_extension != 'SVG': os.remove(self.path)
def test_embedded_svg_with_percentages(self): drawing = svglib.svg2rlg(io.StringIO(textwrap.dedent('''\ <?xml version="1.0"?> <svg xmlns="http://www.w3.org/2000/svg" version="1.1" height="100" width="100"> <rect height="100%" width="100%" x="0" y="0" /> <svg height="15" width="15" x="45" y="45"> <rect fill="black" height="100%" width="100%" x="0" y="0" /> </svg> </svg> '''))) inner_rect = drawing.contents[0].contents[1].contents[0] assert inner_rect.width == 15
def test_png_in_svg_file_like(self): drawing = svglib.svg2rlg(io.StringIO(textwrap.dedent(u'''\ <?xml version="1.0"?> <svg xmlns="http://www.w3.org/2000/svg" version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 210 297" height="297mm" width="210mm"> <image id="refImage" xlink:href="../png/jpeg-required-201-t.png" height="36" width="48" y="77" x="50" /> </svg> '''))) # FIXME: test the error log when we can require pytest >= 3.4 # No image as relative path in file-like input cannot be determined. assert drawing.contents[0].contents == []
def GetSymbol(self): """Returns this color's symbol image data. Lazily created and cached across calls. """ if not self._symbol and self._symbolName: path = os.path.join( os.path.split(__file__)[0], "icons/%s.svg" % self._symbolName) self._symbol = svg2rlg(path) self._symbol.scale(.18, .18) return self._symbol
def post(): # drawing = svg2rlg(StringIO.StringIO(tangelo.request_body())) body = tangelo.request_body().read() f = tempfile.NamedTemporaryFile(delete=False) f.write(body) f.close() # return open(f.name).read() drawing = svg2rlg(f.name) # drawing.renderScale = 1 id = '%030x' % random.randrange(16 ** 30) converted[id] = renderPDF.drawToString(drawing) return {"result": id, "error": None}
def svgToPdfPng(output): img = svg2rlg(output+'.svg') doc = SimpleDocTemplate(output+'.pdf', pagesize=(6*inch,13.2*inch), rightMargin=0, leftMargin=0, topmargin=0, bottommargin=0) docs = [] docs.append(img) doc.build(docs)
def _get_drawing(self, path, filename=None, width=None, height=None, max_width=None, max_height=None): try: drawing = svg2rlg(path) sx=sy=1 drawing.width,drawing.height = drawing.minWidth()*sx, drawing.height*sy if max_height: sy= max_height/drawing.height if drawing.height > max_height else 1 sx = sy elif max_width: sx= max_width/drawing.width if drawing.width > max_width else 1 sy = sx except (AttributeError) as e: logger.debug(e) logger.debug(path) logger.debug(svg2rlg(path)) drawing.scale(sx,sy) return drawing, drawing.width, drawing.height
def display_board(board): board_svg_str = chess.svg.board(board) board_svg_bytes = io.StringIO(board_svg_str) board_rlg = svg2rlg(board_svg_bytes) board_png_str = board_rlg.asString("png") board_png_bytes = io.BytesIO(board_png_str) board_img = mpimg.imread(board_png_bytes, format="PNG") plt.axis('off') plt.imshow(board_img) plt.pause(0.1)
def svg_demo(image_path, output_path): """ Convert an SVG to a PDF """ drawing = svg2rlg(image_path) doc = SimpleDocTemplate(output_path, rightMargin=0, leftMargin=0) story = [] story.append(drawing) doc.build(story)
def make_thumbnail(url, thumbnail_text, color): thumbnail_template_url = "assets\\images\\thumbnail_template.svg" theme_color = color.lstrip("#").lower() color = (int(theme_color[0:2], 16), int( theme_color[2:4], 16), int(theme_color[4:6], 16)) template_svg_file = open(thumbnail_template_url, "r", encoding='UTF8') new_template_svg = open( "assets\\files\\thumbnail_template.svg", "w", encoding='UTF8') template_svg_content = template_svg_file.read() template_svg_change_color = template_svg_content.replace( "red", "#" + theme_color) new_template_svg.write(template_svg_change_color) template_svg_file.close() new_template_svg.close() drawing = svg2rlg("assets\\files\\thumbnail_template.svg") renderPM.drawToFile(drawing, "assets\\files\\template.png", fmt="PNG") image = Image.open('assets\\files\\template.png') font_type_GodoB = ImageFont.truetype('assets\\fonts\\godo\\GodoB.ttf', 60) font_type_GodoM = ImageFont.truetype('assets\\fonts\\godo\\GodoM.ttf', 60) font_type_godoRounded_L = ImageFont.truetype( 'assets\\fonts\\godo\\godoRounded L.ttf', 128) num_X_position = image.size[0] - \ font_type_godoRounded_L.getsize(thumbnail_text[0])[0] - 20 num_Y_position = -12 # 픽셀 세어본거. 폰트 바뀌면 그거에 맞춰서 바꿔줘야 함. X처럼 안한 이유는 폰트가 ㅈ같아서 text_Y_position = [ (image.size[1] / 2) - (font_type_GodoM.getsize(thumbnail_text[1])[1] / 2) - 90, (image.size[1] / 2) - (font_type_GodoB.getsize(thumbnail_text[2])[1] / 2), (image.size[1] / 2) - (font_type_GodoM.getsize(thumbnail_text[3])[1] / 2) + 90 ] draw = ImageDraw.Draw(image) draw.text(xy=(num_X_position, num_Y_position), text=thumbnail_text[0], fill=( 255, 255, 255), font=font_type_godoRounded_L) draw.text(xy=(20, text_Y_position[0]), text=thumbnail_text[1], fill=( 255, 255, 255), font=font_type_GodoM) if theme_color == "ffffff": draw.text(xy=(20, text_Y_position[1]), text=thumbnail_text[2], fill=( 255, 255, 255), font=font_type_GodoB) else: draw.text(xy=( 20, text_Y_position[1]), text=thumbnail_text[2], fill=color, font=font_type_GodoM) draw.text(xy=(20, text_Y_position[2]), text=thumbnail_text[3], fill=( 255, 255, 255), font=font_type_GodoM) # image.show() image.save(url + "thumbnail.png", "PNG")
def svg_to_pdf(svg_file, output_file): """ Method to convert an SVG file to a PDF file, suitable for scholarly publications. This method requires the third-party library svglib. """ # uses svglib to render a SVG to PDF from svglib.svglib import svg2rlg from reportlab.graphics import renderPDF drawing = svg2rlg(svg_file) renderPDF.drawToFile(drawing, output_file)
def importSVG(filename, scale=None, height=None, width=None): if filename: drawing = svg2rlg(filename) if scale: drawing.scale(scale, scale) # the height and width is the reserved drawing place not the size of the grafic if height: drawing.height = height if width: drawing.width = width return drawing
def post(): #drawing = svg2rlg(StringIO.StringIO(tangelo.request_body())) body = tangelo.request_body().read() f = tempfile.NamedTemporaryFile(delete=False) f.write(body) f.close() #return open(f.name).read() drawing = svg2rlg(f.name) #drawing.renderScale = 1 id = '%030x' % random.randrange(16**30) converted[id] = renderPDF.drawToString(drawing) return {"result": id, "error": None}
def generate_emojies(): cwd = pathlib.Path.cwd() for root, dirs, files in os.walk('{}/emojies/svg'.format(cwd)): for name in files: source = os.path.join(root, name) target = os.path.join('{}/emojies'.format(cwd), '{}.pdf'.format(name.split('.')[0].upper())) drawing = svg2rlg(source) renderPDF.drawToFile(drawing, target) print('coverting', target)
def test_external_svg_in_svg(self): path = join(TEST_ROOT, "samples", "others", "svg_in_svg.svg") drawing = svglib.svg2rlg(path) img_group = drawing.contents[0].contents[0] # First image points to SVG rendered as a group assert isinstance(img_group.contents[0], Group) assert isinstance(img_group.contents[0].contents[0].contents[0], Rect) assert img_group.contents[0].transform, (1, 0, 0, 1, 200.0, 100.0) # Second image points directly to a Group with Rect element assert isinstance(img_group.contents[1], Group) assert isinstance(img_group.contents[1].contents[0], Rect) assert img_group.contents[1].transform, (1, 0, 0, 1, 100.0, 200.0)
def draw_svg(self, canvas, path, xpos=0, ypos=0, xsize=None, ysize=None): from reportlab.graphics import renderPDF from svglib.svglib import svg2rlg drawing = svg2rlg(path) xL, yL, xH, yH = drawing.getBounds() if xsize: drawing.renderScale = xsize / (xH - xL) if ysize: drawing.renderScale = ysize / (yH - yL) renderPDF.draw(drawing, canvas, xpos, ypos, showBoundary=self.show_boundaries)
def test_no_fill_on_shape(self): """ Any shape with no fill property should set black color in rlg syntax. """ drawing = svglib.svg2rlg(io.StringIO(textwrap.dedent(u'''\ <?xml version="1.0"?> <svg xmlns="http://www.w3.org/2000/svg" width="1200" height="800" viewBox="0 0 36 24"> <rect y="10" width="36" height="4"/> </svg> '''))) assert drawing.contents[0].contents[0].fillColor == colors.black
def getGeometryImage(cursor, tableName, id): sql = "SELECT AsSvg(geometry) FROM '" + tableName + "' WHERE id =" + `id` cursor.execute(sql) data = cursor.fetchall() t = "x*x, y*y" fig = Fig(Path(data[0][0], fill="blue", local="true"), trans=t).SVG() svgfig._canvas_defaults["width"] = "100px" svgfig._canvas_defaults["height"] = "100px" svgfig._canvas_defaults["viewBox"] = "0 0 100 100" fig.save(here + "tmp.svg") svg = svg2rlg(here + "tmp.svg") os.remove(here + "tmp.svg") return svg
def test_nonzero_origin(self): drawing = svglib.svg2rlg(io.StringIO(textwrap.dedent(u'''\ <?xml version="1.0"?> <svg xmlns="http://www.w3.org/2000/svg" width="1200" height="800" viewBox="-60 -40 120 80"> <g fill="#E70013"> <rect x="-60" y="-40" width="120" height="80"/> </g> </svg> '''))) # Main group coordinates are translated to match the viewBox origin assert drawing.contents[0].transform == (1, 0, 0, -1, 60.0, 40.0)
def test_fillopacity(self): """ The fill-opacity property set the alpha of the color. """ drawing = svglib.svg2rlg(io.StringIO(textwrap.dedent(u'''\ <?xml version="1.0"?> <svg version="1.1" xmlns="http://www.w3.org/2000/svg" width="660" height="480"> <polygon id="triangle" points="0,-29.14 -25.23, 14.57 25.23, 14.57" stroke="#0038b8" stroke-width="5.5" fill-opacity="0"/> </svg> '''))) assert drawing.contents[0].contents[0].fillColor == colors.Color(0, 0, 0, 0)
def test0(self): "Test converting flag SVG files to PDF using svglib." paths = glob.glob("%s/*" % self.folderPath) paths = [p for p in paths if splitext(p.lower())[1] in [".svg", ".svgz"]] for i, path in enumerate(paths): print("working on [%d]" % i, path) # convert drawing = svglib.svg2rlg(path) # save as PDF base = splitext(path)[0] + '-svglib.pdf' renderPDF.drawToFile(drawing, base, showBoundary=0)
def _create_section(self, products, index): data = [] for index, config in enumerate(products): if index < 5: product = products[config] data.append([svg2rlg('armless-sofa.svg'), config, product['export_price']]) table = Table(data) table.setStyle(TableStyle([('GRID', (0, 0), (-1, -1), 1, colors.CMYKColor(black=60)), ('LEFTPADDING', (0, 0), (-1, -1), 0), ('VALIGN', (0, 0), (-1, -1), 'MIDDLE')])) return table
def test_convert_pdf(self): "Test convert sample SVG files to PDF using svglib." paths = glob.glob("%s/samples/misc/*" % TEST_ROOT) paths = [p for p in paths if splitext(p.lower())[1] in [".svg", ".svgz"]] for i, path in enumerate(paths): print("working on [%d] %s" % (i, path)) # convert drawing = svglib.svg2rlg(path) # save as PDF base = splitext(path)[0] + '-svglib.pdf' renderPDF.drawToFile(drawing, base, showBoundary=0)
def test_convert_pdf_png(self): """ Test converting W3C SVG files to PDF and PNG using svglib. ``renderPM.drawToFile()`` used in this test is known to trigger an error sometimes in reportlab which was fixed in reportlab 3.3.26. See https://github.com/deeplook/svglib/issues/47 """ exclude_list = [ "paint-stroke-06-t.svg", "coords-trans-09-t.svg", # renderPDF issue (div by 0) # Unsupported 'transform="ref(svg, ...)"' expression "coords-constr-201-t.svg", "coords-constr-202-t.svg", "coords-constr-203-t.svg", "coords-constr-204-t.svg", ] paths = glob.glob("%s/svg/*.svg" % self.folder_path) msg = "Destination folder '%s/svg' not found." % self.folder_path assert len(paths) > 0, msg for i, path in enumerate(paths): print("working on [%d] %s" % (i, path)) if basename(path) in exclude_list: print("excluded (to be tested later)") continue # convert drawing = svglib.svg2rlg(path) # save as PDF base = splitext(path)[0] + '-svglib.pdf' renderPDF.drawToFile(drawing, base, showBoundary=0) # save as PNG # (endless loop for file paint-stroke-06-t.svg) base = splitext(path)[0] + '-svglib.png' try: # Can trigger an error in reportlab < 3.3.26. renderPM.drawToFile(drawing, base, 'PNG') except TypeError: print('Svglib: Consider upgrading reportlab to version >= 3.3.26!') raise
def test_transform_inherited_by_use(self): drawing = svglib.svg2rlg(io.StringIO(textwrap.dedent(u'''\ <?xml version="1.0"?> <svg version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" width="900" height="600"> <g id="c"> <path id="t" d="M 0,-100 V 0 H 50" transform="rotate(18 0,-100)"/> <use xlink:href="#t" transform="scale(-1,1)"/> </g> </svg> '''))) cgroup_node = drawing.contents[0].contents[0] assert ( cgroup_node.contents[0].transform == cgroup_node.contents[1].contents[0].transform ), "The transform of the original path is different from the transform of the reused path."
def test_use_forward_reference(self): """ Sometimes, a node definition pointed to by xlink:href can appear after it has been referenced. But the order should remain. """ drawing = svglib.svg2rlg(io.StringIO(textwrap.dedent(u'''\ <?xml version="1.0"?> <svg version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" width="900" height="600"> <use xlink:href="#back" x="-100"/> <rect id="back" x="42" y="42" width="416" height="216" fill="#007a5e"/> </svg> '''))) assert len(drawing.contents[0].contents) == 2 assert isinstance(drawing.contents[0].contents[0], Group) assert isinstance(drawing.contents[0].contents[1], Rect)
def render(self): doc = SimpleDocTemplate( NamedTemporaryFile(), pagesize=landscape(letter)) parts = [] pSVG = self.request.form.get('pSVG1') tf = tempfile.NamedTemporaryFile() tf.write(unicode(pSVG).encode('utf-8')) tf.seek(0) drawing = svg2rlg(tf.name) drawing.renderScale = 0.57 self.frontpage(parts) parts.append(drawing) doc.build(parts, onFirstPage=self.headerfooter, onLaterPages=self.headerfooter) pdf = doc.filename pdf.seek(0) return pdf.read()
def test_use_node_with_unclosed_path(self): """ When a <use> node references an unclosed path (which is a group with two different paths for filling and stroking), the use properties shouldn't affect the no-stroke property of the fake stroke-only path. """ drawing = svglib.svg2rlg(io.StringIO(textwrap.dedent(u'''\ <?xml version="1.0"?> <svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="900" height="600" viewBox="0 0 9 6"> <defs> <path d="M0,0 4.5,3 0,6" id="X"/> </defs> <use xlink:href="#X" fill="#f00" stroke="#ffb612" stroke-width="2"/> </svg> '''))) use_group = drawing.contents[0].contents[0].contents[0] assert use_group.contents[0].getProperties()['strokeWidth'] == 0 assert use_group.contents[0].getProperties()['strokeColor'] is None
def test_use_node_properties(self): """ Properties on the use node apply to the referenced item. """ drawing = svglib.svg2rlg(io.StringIO(textwrap.dedent(u'''\ <?xml version="1.0"?> <svg version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" width="900" height="600"> <path id="a" fill="#FF0000" d="M-15 37.57h60L-15 0v80h60l-60-60z"/> <use stroke="#003893" stroke-width="5" xlink:href="#a"/> <use stroke="#003893" stroke-width="2" xlink:href="#a"/> </svg> '''))) use_path1 = drawing.contents[0].contents[1].contents[0].contents[0] use_path2 = drawing.contents[0].contents[2].contents[0].contents[0] # Attribute from <path> node assert use_path1.fillColor == colors.Color(1, 0, 0, 1) # Attribute from <use> node assert use_path1.strokeWidth == 5 assert use_path2.strokeWidth == 2
def saveQrCodeSVG(filename,text, ptext): factory = qrcode.image.svg.SvgPathImage img = qrcode.make(text, image_factory=factory,box_size=30, border=4) svf = open(filename,"w") img.save(svf,"SVG") svf.close() text_svg_fname = filename+".text.svg" merged_svg_name = filename+'.merged.svg' svg_document = svgwrite.Drawing(filename = text_svg_fname, size = ("41mm", "41mm")) # svg_document.add(svg_document.rect(insert = (0, 0), # size = ("41mm", "41mm"), # stroke_width = "1", # stroke = "black", # fill = "rgb(240,240,240)")) svg_document.add(svg_document.text(ptext, insert = (106, 10), fill = "rgb(0,0,0)", style = "font-size:1mm; font-family:Arial")) svg_document.add(svg_document.text(text, insert = (7.5, 117), fill = "rgb(0,0,0)", style = "font-size:1.8mm; font-family:Arial")) svg_document.save() # dwg.add(dwg.text('Test', insert=(0, 0.2), fill='red')) # ##PDF # drawing = svg2rlg(filename) # renderPDF.drawToFile(drawing, filename+".pdf") template = st.fromfile(text_svg_fname) second_svg = st.fromfile(filename) template.append(second_svg) template.save(merged_svg_name) drawing = svg2rlg(merged_svg_name) renderPDF.drawToFile(drawing, filename+".pdf")
def test0(self): "Test sample SVG files included in svglib test suite." paths = glob.glob("samples/misc/*") paths = [p for p in paths if splitext(p.lower())[1] in [".svg", ".svgz"]] for i, path in enumerate(paths): print "working on [%d]" % i, path # convert try: drawing = svglib.svg2rlg(path) except: print "could not convert [%d]" % i, path continue # save as PDF base = splitext(path)[0] + '-svglib.pdf' try: renderPDF.drawToFile(drawing, base, showBoundary=0) except: print "could not save as PDF [%d]" % i, path
def test0(self): "Test converting symbol SVG files to PDF using svglib." paths = glob.glob("%s/*" % self.folderPath) paths = [p for p in paths if splitext(p.lower())[1] in [".svg", ".svgz"]] for i, path in enumerate(paths): print "working on [%d]" % i, path # convert try: drawing = svglib.svg2rlg(path) except: print "could not convert [%d]" % i, path continue # save as PDF base = splitext(path)[0] + '-svglib.pdf' try: renderPDF.drawToFile(drawing, base, showBoundary=0) except: print "could not save as PDF [%d]" % i, path
def test0(self): "Test converting W3C SVG files to PDF using svglib." excludeList = [ "paint-stroke-06-t.svg", ] paths = glob.glob("%s/svg/*.svg" % self.folderPath) msg = "Destination folder '%s/svg' not found." % self.folderPath self.failUnless(len(paths) > 0, msg) for i, path in enumerate(paths): print "working on [%d]" % i, path if basename(path) in excludeList: print "excluded (to be tested later)" continue # convert try: drawing = svglib.svg2rlg(path) except: print "could not convert [%d]" % i, path continue # save as PDF base = splitext(path)[0] + '-svglib.pdf' try: renderPDF.drawToFile(drawing, base, showBoundary=0) except: print "could not save as PDF [%d]" % i, path # save as PNG # (endless loop for file paint-stroke-06-t.svg) base = splitext(path)[0] + '-svglib.png' try: renderPM.drawToFile(drawing, base, 'PNG') except: print "could not save as PNG [%d]" % i, path
def test_tspan_position(self): """ The x/y positions of a tspan are either relative to the current text position, or can be absoluted by specifying the x/y attributes. """ drawing = svglib.svg2rlg(io.StringIO(textwrap.dedent(u'''\ <?xml version="1.0"?> <svg width="777" height="267"> <text x="10" style="fill:#000000; stroke:none; font-size:28;"> <tspan>TITLE 1</tspan> <!-- position relative to current text position--> <tspan>(after title)</tspan> <!-- absolute position from parent start --> <tspan x="-10.75" y="33.487">Subtitle</tspan> </text> </svg> '''))) main_group = drawing.contents[0] assert main_group.contents[0].contents[0].x == 10 assert main_group.contents[0].contents[0].y == 0 assert main_group.contents[0].contents[1].x > 10 assert main_group.contents[0].contents[1].y == 0 assert main_group.contents[0].contents[2].x == -0.75 # 10 - 10.75 assert main_group.contents[0].contents[2].y == -33.487
from builtins import input import zipfile import os from svglib.svglib import svg2rlg from reportlab.graphics import renderPDF from PyPDF2 import PdfFileMerger, PdfFileReader # Enter file name fname = input('Notebook file: ') # Opens file f = zipfile.ZipFile(fname) # Get pages with extension .svg svgpages = [name for name in f.namelist() if name.endswith('.svg')] # Extract .svg pages [f.extract(svgpage) for svgpage in svgpages] # Creates list with pdf names (same as svg page names) pdfpages = [svgpage.split(".")[0]+".pdf" for svgpage in svgpages] # Creates pdf pages for svgpage, pdfpage in zip(svgpages, pdfpages): svgpage = svg2rlg(svgpage) renderPDF.drawToFile(svgpage, pdfpage) # Merges pdf pages in document.pdf merger = PdfFileMerger() [merger.append(PdfFileReader(file(pdfpage, 'rb'))) for pdfpage in pdfpages] # Writes pdf file with all pages with same name as notebook file merger.write(fname.split(".")[0]+".pdf") # Delete intermediary files [os.remove(svgfile) for svgfile in svgpages] [os.remove(pdffile) for pdffile in pdfpages]
__author__ = 'morrj140' import svgwrite dwg = svgwrite.Drawing('test.svg', profile='tiny') dwg.add(dwg.line((0, 0), (10, 0), stroke=svgwrite.rgb(10, 10, 16, '%'))) dwg.add(dwg.text('Test', insert=(0, 0.2))) dwg.save() svg_document = svgwrite.Drawing(filename = "test-svgwrite.svg", size = ("800px", "600px")) svg_document.add(svg_document.rect(insert = (0, 0), size = ("200px", "100px"), stroke_width = "1", stroke = "black", fill = "rgb(255,255,0)")) svg_document.add(svg_document.text("Hello World", insert = (210, 110))) print(svg_document.tostring()) svg_document.save() from svglib.svglib import svg2rlg from reportlab.graphics import renderPDF drawing = svg2rlg("test-svgwrite.svg") renderPDF.drawToFile(drawing, "file.pdf")