ssbu_lokrez/lokrez/export.py

132 lines
3.7 KiB
Python

import os
import subprocess
import jinja2
# =============================================================================
def generate_outfile(
templatesdir,
templatename,
context,
outfilename,
log = None,
):
# Template rendering
# -------------------------------------------------------------------------
log.info("Generating SVG using '{}' template".format(templatename))
jj2_env = jinja2.Environment(
loader = jinja2.FileSystemLoader( templatesdir )
)
try:
jj2_tpl = jj2_env.get_template(
os.path.join(
templatename,
"template.svg.j2",
)
)
except:
log.error("Could not find template '{}'".format(templatename))
return None
extension = outfilename.split(".")[-1]
# To SVG
# -------------------------------------------------------------------------
if extension == "svg":
jj2_tpl.stream(context).dump( outfilename )
return outfilename
# To PNG with inkscape
# -------------------------------------------------------------------------
if extension == "png":
try:
log.info("Exporting to {} using inkscape".format(extension))
import subprocess
jj2_tpl.stream(context).dump( "tmp.svg" )
inkscape_process = subprocess.Popen(
[
"inkscape",
"tmp.svg",
"--export-filename",
outfilename,
],
stdout = subprocess.PIPE,
stderr = subprocess.STDOUT,
universal_newlines = True,
)
for line_out in iter(inkscape_process.stdout.readline, ""):
log.debug(line_out)
inkscape_process.stdout.close()
rv = inkscape_process.wait()
if rv != 0:
raise Exception(
"Bad inkscape return code '{}'" \
.format(inkscape_process.returncode)
)
os.unlink("tmp.svg")
return outfilename
except Exception as e:
log.warning("Failed to export with inkscape")
try:
os.unlink("tmp.svg")
except:
pass
log.debug(e)
# To png, pdf or ps with cairosvg
# -------------------------------------------------------------------------
if extension in [ "png", "pdf", "ps" ]:
log.info("Exporting to {} using cairosvg".format(extension))
try:
import cairosvg
except ImportError as e:
log.error(
"Failed to export to '{}' with cairosvg" \
.format(
outfilename,
)
)
log.debug(e)
svg_str = jj2_tpl.render(context)
if extension == "png":
conversion_fun = cairosvg.svg2png
elif extension == "pdf":
conversion_fun = cairosvg.svg2pdf
elif extension == "ps":
conversion_fun = cairosvg.svg2ps
conversion_fun(
bytestring = svg_str,
write_to = outfilename,
)
return outfilename
# To unsupported format
# -------------------------------------------------------------------------
log.error(
"Can't export to '{}' : unsupported format '{}'" \
.format(
outfilename,
extension,
)
)
return None