Skip to content

Instantly share code, notes, and snippets.

@Balletie
Last active March 13, 2018 13:50
Show Gist options
  • Save Balletie/a3ccf434f8ec492e47fff4589225d5cb to your computer and use it in GitHub Desktop.
Save Balletie/a3ccf434f8ec492e47fff4589225d5cb to your computer and use it in GitHub Desktop.
import subprocess
from sphinx.errors import ExtensionError
from sphinx.util import logging
from sphinx.transforms.post_transforms.images import ImageConverter
from sphinx.util.osutil import ENOENT, EPIPE, EINVAL
logger = logging.getLogger(__name__)
class InkscapeConverter(ImageConverter):
conversion_rules = [('image/svg+xml', 'application/pdf')]
def is_available(self):
return True
def convert(self, from_file, to_file):
try:
args = ["inkscape", "-D", "-A", to_file, from_file]
logger.info("Invoking %r ...", args)
p = subprocess.Popen(args, stdin=subprocess.PIPE, stdout=subprocess.PIPE)
except OSError as err:
if err.errno != ENOENT:
raise
logger.warning("inkscape not found, make sure it's installed and on your PATH.")
return False
try:
stdout, stderr = p.communicate()
except (OSError, IOError) as err:
if err.errno not in (EPIPE, EINVAL):
raise
stdout, stderr = p.stdout.read(), p.stderr.read()
p.wait()
if p.returncode != 0:
raise ExtensionError("inkscape exited with error:\n%s\n", stderr)
return True
class RSVGConverter(ImageConverter):
conversion_rules = [('image/svg+xml', 'application/pdf')]
def is_available(self):
return True
def convert(self, from_file, to_file):
try:
args = ["rsvg-convert", "-f", "pdf", from_file, "-o", to_file]
logger.info("Invoking %r ...", args)
p = subprocess.Popen(args, stdin=subprocess.PIPE, stdout=subprocess.PIPE)
except OSError as err:
if err.errno != ENOENT:
raise
logger.warning("rsvg-convert not found, make sure it's installed and on your PATH.")
return False
try:
stdout, stderr = p.communicate()
except (OSError, IOError) as err:
if err.errno not in (EPIPE, EINVAL):
raise
stdout, stderr = p.stdout.read(), p.stderr.read()
p.wait()
if p.returncode != 0:
raise ExtensionError("rsvg-convert exited with error:\n%s\n", stderr)
return True
def setup(app):
#app.add_post_transform(RSVGConverter)
app.add_post_transform(InkscapeConverter)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment