From ef6dd6e23e57ebfd48657c7c3dbfadac71a249ba Mon Sep 17 00:00:00 2001 From: mippolito Date: Fri, 24 Mar 2017 14:13:26 +0100 Subject: [PATCH] Adds render_to_html() method This allows to render a graph to an html string. It does exactly the same as render_in_browser(), but it returns the string instead of opening the result in the browser. This is useful if you need to render the graph to html to embed it in a webpage. --- pygal/graph/public.py | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) diff --git a/pygal/graph/public.py b/pygal/graph/public.py index eb6e43f..7df7a3a 100644 --- a/pygal/graph/public.py +++ b/pygal/graph/public.py @@ -78,6 +78,25 @@ class PublicApi(BaseGraph): from pyquery import PyQuery as pq return pq(self.render(**kwargs), parser='html') + def render_to_html(self, **kwargs): + """ + Renders the graph to an html string. + The result is the same as render_in_browser(), but returned as a string + so that it can be embedded into another html document. + """ + try: + from lxml.etree import ElementTree + except ImportError: + raise ImportError('You must install lxml to use render in browser') + + from cStringIO import StringIO + + buf = StringIO() + doc = ElementTree(self.render_tree(**kwargs)) + doc.write(buf, method="html", encoding='utf-8') + + return buf.getvalue().decode('utf-8') + def render_in_browser(self, **kwargs): """Render the graph, open it in your browser with black magic""" try: