Example #1
0
def init_math(app):
    """
        This is a dummy math extension.

        It's a hack, but if you want math in a PDF via pdfbuilder, and don't want to
        enable pngmath or jsmath, then enable this one.

        :copyright: Copyright 2007-2009 by the Sphinx team, see AUTHORS.
        :license: BSD, see LICENSE for details.
    """
    from sphinx.errors import SphinxError
    try:
        # Sphinx 0.6.4 and later
        from sphinx.ext.mathbase import setup_math as mathbase_setup
    except ImportError:
        try:
            # Sphinx 0.6.3
            from sphinx.ext.mathbase import setup as mathbase_setup
        except ImportError:
            _, e, _ = sys.exc_info()
            log.error('Error importing sphinx math extension: %s', e)

    class MathExtError(SphinxError):
        category = 'Math extension error'


    def html_visit_math(self, node):
        self.body.append(node['latex'])
        raise nodes.SkipNode

    def html_visit_displaymath(self, node):
        self.body.append(node['latex'])
        raise nodes.SkipNode

    mathbase_setup(app, (html_visit_math, None), (html_visit_displaymath, None))
Example #2
0
 def gather_elements(self, client, node, style):
     # Based on the graphviz extension
     global graphviz_warn
     try:
         # Is vectorpdf enabled?
         if hasattr(VectorPdf, 'load_xobj'):
             # Yes, we have vectorpdf
             fname, outfn = sphinx.ext.graphviz.render_dot(
                 node['builder'], node['code'], node['options'], 'pdf')
         else:
             # Use bitmap
             if not graphviz_warn:
                 log.warning(
                     'Using graphviz with PNG output. You get much better results if you enable the vectorpdf extension.'
                 )
                 graphviz_warn = True
             fname, outfn = sphinx.ext.graphviz.render_dot(
                 node['builder'], node['code'], node['options'], 'png')
         if outfn:
             client.to_unlink.append(outfn)
             client.to_unlink.append(outfn + '.map')
         else:
             # Something went very wrong with graphviz, and
             # sphinx should have given an error already
             return []
     except sphinx.ext.graphviz.GraphvizError as exc:
         log.error('dot code %r: ' % node['code'] + str(exc))
         return [Paragraph(node['code'], client.styles['code'])]
     return [MyImage(filename=outfn, client=client)]
Example #3
0
    def handle_include(self, fname):
        # Ugly, violates DRY, etc., but I'm not about to go
        # figure out how to re-use docutils include file
        # path processing!

        for prefix in ('', os.path.dirname(self.sourcef.name)):
            try:
                f = open(os.path.join(prefix, fname), 'rb')
            except IOError:
                continue
            else:
                break
        else:
            log.error("Could not find include file %s", fname)
            self.changed = True
            return

        # Recursively call this class to process include files.
        # Extract all the information from the included file.

        inc = Preprocess(f, True, self.widthcount)
        self.widthcount = inc.widthcount
        if 'styles' in self.styles and 'styles' in inc.styles:
            self.styles['styles'].update(inc.styles.pop('styles'))
        self.styles.update(inc.styles)
        if inc.changed:
            self.changed = True
            if not inc.keep:
                return
            fname = inc.result.name
        self.result.extend(['', '', '.. include:: ' + fname, ''])
    def handle_widths(self, chunk):
        """ Insert a unique style in the stylesheet, and reference it
            from a .. class:: comment.
        """
        self.changed = True
        chunk = chunk.replace(",", " ").replace("%", " ").split()
        if not chunk:
            log.error("no widths specified in .. widths ::")
            return
        parent = chunk[0][0].isalpha() and chunk.pop(0) or "table"
        values = [float(x) for x in chunk]
        total = sum(values)
        values = [int(round(100 * x / total)) for x in values]
        while 1:
            total = sum(values)
            if total > 100:
                values[values.index(max(values))] -= 1
            elif total < 100:
                values[values.index(max(values))] += 1
            else:
                break

        values = ["%s%%" % x for x in values]
        self.widthcount += 1
        stylename = "embeddedtablewidth%d" % self.widthcount
        self.styles.setdefault("styles", {})[stylename] = dict(parent=parent, colWidths=values)
        self.result.extend(["", "", ".. class:: " + stylename, ""])
Example #5
0
 def raster(self, filename, client):
     """Returns a URI to a rasterized version of the image"""
     cache = self.source_filecache.setdefault(client, {})
     pngfname = cache.get(filename + '_raster')
     if pngfname is None:
         tmpf, pngfname = tempfile.mkstemp(suffix='.png')
         os.close(tmpf)
         client.to_unlink.append(pngfname)
         cache[filename + '_raster'] = pngfname
         # which version of inkscape?
         cmd = [progname, '--version']
         exitcode, out, err = InkscapeImage.run_cmd(cmd)
         if out.startswith('Inkscape 0.'):
             # Inkscape 0.x uses -A
             cmd = [
                 progname,
                 os.path.abspath(filename), '-e', pngfname, '-d',
                 str(client.def_dpi)
             ]
         else:
             # Inkscape 1.x uses --export-file
             cmd = [
                 progname,
                 os.path.abspath(filename),
                 '--export-file=%s' % pngfname, '-d',
                 str(client.def_dpi)
             ]
         try:
             subprocess.call(cmd)
             return pngfname
         except OSError:
             log.error("Failed to run command: %s", ' '.join(cmd))
             raise
     return None
    def handle_include(self, fname):
        # Ugly, violates DRY, etc., but I'm not about to go
        # figure out how to re-use docutils include file
        # path processing!
        for prefix in ('', os.path.dirname(self.sourcef.name)):
            if os.path.exists(os.path.join(prefix, fname)):
                break
        else:
            log.error("Could not find include file %s", fname)
            self.changed = True
            return

        # Recursively call this class to process include files.
        # Extract all the information from the included file.
        with open(os.path.join(prefix, fname), 'r') as f:
            inc = Preprocess(f, True, self.widthcount)
            self.widthcount = inc.widthcount
            if 'styles' in self.styles and 'styles' in inc.styles:
                self.styles['styles'].update(inc.styles.pop('styles'))
            self.styles.update(inc.styles)
            if inc.changed:
                self.changed = True
                if not inc.keep:
                    return
                fname = inc.result.name
            self.result.extend(['', '', '.. include:: ' + fname, ''])
Example #7
0
    def __init__(self,
                 filename,
                 width=None,
                 height=None,
                 kind='direct',
                 mask=None,
                 lazy=True,
                 srcinfo=None):
        client, uri = srcinfo
        cache = self.source_filecache.setdefault(client, {})
        pdffname = cache.get(filename)
        if pdffname is None:
            tmpf, pdffname = tempfile.mkstemp(suffix='.pdf')
            os.close(tmpf)
            client.to_unlink.append(pdffname)
            cache[filename] = pdffname
            cmd = [progname, os.path.abspath(filename), '-A', pdffname]
            try:
                subprocess.call(cmd)
            except OSError:
                log.error("Failed to run command: %s", ' '.join(cmd))
                raise
            self.load_xobj((client, pdffname))

        pdfuri = uri.replace(filename, pdffname)
        pdfsrc = client, pdfuri
        VectorPdf.__init__(self, pdfuri, width, height, kind, mask, lazy,
                           pdfsrc)
Example #8
0
    def handle_widths(self, chunk):
        self.changed = True
        chunk = chunk.replace(',', ' ').replace('%', ' ').split()
        if not chunk:
            log.error('no widths specified in .. widths ::')
            return
        parent = chunk[0][0].isalpha() and chunk.pop(0) or 'table'
        values = [float(x) for x in chunk]
        total = sum(values)
        values = [int(round(100 * x / total)) for x in values]
        while 1:
            total = sum(values)
            if total > 100:
                values[index(max(values))] -= 1
            elif total < 100:
                values[index(max(values))] += 1
            else:
                break

        values = ['%s%%' % x for x in values]
        self.widthcount += 1
        stylename = 'embeddedtablewidth%d' % self.widthcount
        self.styles.setdefault('styles',
                               {})[stylename] = dict(parent=parent,
                                                     colWidths=values)
        self.result.extend(['', '', '.. class:: ' + stylename, ''])
    def handle_widths(self, chunk):
        ''' Insert a unique style in the stylesheet, and reference it
            from a .. class:: comment.
        '''
        self.changed = True
        chunk = chunk.replace(',', ' ').replace('%', ' ').split()
        if not chunk:
            log.error('no widths specified in .. widths ::')
            return
        parent = chunk[0][0].isalpha() and chunk.pop(0) or 'table'
        values = [float(x) for x in chunk]
        total = sum(values)
        values = [int(round(100 * x / total)) for x in values]
        while 1:
            total = sum(values)
            if total > 100:
                values[values.index(max(values))] -= 1
            elif total < 100:
                values[values.index(max(values))] += 1
            else:
                break

        values = ['%s%%' % x for x in values]
        self.widthcount += 1
        stylename = 'embeddedtablewidth%d' % self.widthcount
        self.styles.setdefault('styles', {})[stylename] = dict(parent=parent, colWidths=values)
        self.result.extend(['', '', '.. class:: ' + stylename, ''])
Example #10
0
 def handle_style(self, chunk):
     self.changed = True
     if chunk:
         log.error(".. styles:: does not recognize string %s" % repr(chunk))
         return
     source = self.source
     data = source and source.pop().splitlines() or []
     data.reverse()
     mystyles = []
     while data:
         myline = data.pop().rstrip()
         if not myline:
             continue
         if myline.lstrip() == myline:
             data.append(myline)
             break
         mystyles.append(myline)
     data.reverse()
     data.append('')
     source.append('\n'.join(data))
     if not mystyles:
         log.error("Empty .. styles:: block found")
     indent = min(len(x) - len(x.lstrip()) for x in mystyles)
     mystyles = [x[indent:] for x in mystyles]
     mystyles.append('')
     mystyles = '\n'.join(mystyles)
     try:
         styles = rson_loads(mystyles)
         self.styles.setdefault('styles', {}).update(styles)
     except ValueError, e:  # Error parsing the JSON data
         log.critical('Error parsing stylesheet "%s": %s'%\
             (mystyles, str(e)))
Example #11
0
def init_math(app):
    """
    This is a dummy math extension.

    It's a hack, but if you want math in a PDF via pdfbuilder, and don't want
    to enable pngmath or jsmath, then enable this one.

    :copyright: Copyright 2007-2009 by the Sphinx team, see AUTHORS.
    :license: BSD, see LICENSE for details.
    """
    from sphinx.errors import SphinxError
    try:
        # Sphinx 0.6.4 and later
        from sphinx.ext.mathbase import setup_math as mathbase_setup
    except ImportError:
        try:
            # Sphinx 0.6.3
            from sphinx.ext.mathbase import setup as mathbase_setup
        except ImportError as e:
            log.error('Error importing sphinx math extension: %s', e)

    class MathExtError(SphinxError):
        category = 'Math extension error'

    def html_visit_math(self, node):
        self.body.append(node['latex'])
        raise nodes.SkipNode

    def html_visit_displaymath(self, node):
        self.body.append(node['latex'])
        raise nodes.SkipNode

    mathbase_setup(app, (html_visit_math, None),
                   (html_visit_displaymath, None))
    def handle_include(self, fname):
        # Ugly, violates DRY, etc., but I'm not about to go
        # figure out how to re-use docutils include file
        # path processing!

        for prefix in ("", os.path.dirname(self.sourcef.name)):
            try:
                f = open(os.path.join(prefix, fname), "rb")
            except IOError:
                continue
            else:
                break
        else:
            log.error("Could not find include file %s", fname)
            self.changed = True
            return

        # Recursively call this class to process include files.
        # Extract all the information from the included file.

        inc = Preprocess(f, True, self.widthcount)
        self.widthcount = inc.widthcount
        if "styles" in self.styles and "styles" in inc.styles:
            self.styles["styles"].update(inc.styles.pop("styles"))
        self.styles.update(inc.styles)
        if inc.changed:
            self.changed = True
            if not inc.keep:
                return
            fname = inc.result.name
        self.result.extend(["", "", ".. include:: " + fname, ""])
Example #13
0
 def gather_elements(self, client, node, style):
     try:
         for entry in node['entries']:
             client.pending_targets.append(docutils.nodes.make_id(entry[2]))
     except IndexError:
         if node['entries']:
             log.error("Can't process index entry: %s [%s]",
                       node['entries'], nodeid(node))
     return []
Example #14
0
 def __init__(self, data, colWidths, style, padding=3):
     if len(data) != 1 or len(data[0]) != 2:
         log.error('SplitTable can only be 1 row and two columns!')
         sys.exit(1)
     DelayedTable.__init__(self, data, colWidths, style)
     self.padding, p1, p2, p3, p4 = tablepadding(padding)
     self.style._cmds.insert(0, p1)
     self.style._cmds.insert(0, p2)
     self.style._cmds.insert(0, p3)
     self.style._cmds.insert(0, p4)
Example #15
0
 def __init__(self, data, colWidths, style, padding=3):
     if len(data) != 1 or len(data[0]) != 2:
         log.error('SplitTable can only be 1 row and two columns!')
         sys.exit(1)
     DelayedTable.__init__(self, data, colWidths, style)
     self.padding, p1, p2, p3, p4 = tablepadding(padding)
     self.style._cmds.insert(0, p1)
     self.style._cmds.insert(0, p2)
     self.style._cmds.insert(0, p3)
     self.style._cmds.insert(0, p4)
Example #16
0
    def __init__(self, *args):
        if len(args) < 1:
            args = [None, 1]  # No transition
        # See if we got a valid transition effect name
        if args[0] not in self.PageTransitionEffects:
            log.error('Unknown transition effect name: %s' % args[0])
            args[0] = None
        elif len(args) == 1:
            args.append(1)

        # FIXME: validate more
        self.args = args
Example #17
0
    def __init__(self, *args):
        if len(args) < 1:
            args = [None, 1]  # No transition
        # See if we got a valid transition effect name
        if args[0] not in self.PageTransitionEffects:
            log.error('Unknown transition effect name: %s' % args[0])
            args[0] = None
        elif len(args) == 1:
            args.append(1)

        # FIXME: validate more
        self.args = args
Example #18
0
 def __init__(self, s, label=None, fontsize=12, color='black'):
     self.s = s
     self.label = label
     self.fontsize = fontsize
     self.color = color
     if HAS_MATPLOTLIB:
         self.parser = mathtext.MathTextParser("Pdf")
     else:
         log.error('Math support not available, some parts of this ' +
                   'document will be rendered incorrectly. Install ' +
                   'matplotlib.')
     Flowable.__init__(self)
     self.hAlign = 'CENTER'
 def __init__(self, s, label=None, fontsize=12, color='black'):
     self.s = s
     self.label = label
     self.fontsize = fontsize
     self.color = color
     if HAS_MATPLOTLIB:
         self.parser = mathtext.MathTextParser("Pdf")
     else:
         log.error('Math support not available, some parts of this ' +
                   'document will be rendered incorrectly. Install ' +
                   'matplotlib.')
     Flowable.__init__(self)
     self.hAlign = 'CENTER'
Example #20
0
def parseRaw(data, node):
    """
    Parse and process a simple DSL to handle creation of flowables.

    Supported (can add others on request):

      * PageBreak
      * Spacer width, height
    """
    elements = []
    lines = data.splitlines()
    for line in lines:
        lexer = shlex.shlex(line)
        lexer.whitespace += ','
        tokens = list(lexer)
        if not tokens:
            continue  # Empty line
        command = tokens[0]
        if command == 'PageBreak':
            if len(tokens) == 1:
                elements.append(MyPageBreak())
            else:
                elements.append(MyPageBreak(tokens[1]))
        elif command == 'EvenPageBreak':
            if len(tokens) == 1:
                elements.append(MyPageBreak(breakTo='even'))
            else:
                elements.append(MyPageBreak(tokens[1], breakTo='even'))
        elif command == 'OddPageBreak':
            if len(tokens) == 1:
                elements.append(MyPageBreak(breakTo='odd'))
            else:
                elements.append(MyPageBreak(tokens[1], breakTo='odd'))
        # TODO: Where does CondPageBreak come from?
        # elif command == 'FrameBreak':
        #     if len(tokens) == 1:
        #         elements.append(CondPageBreak(99999))
        #     else:
        #         elements.append(CondPageBreak(float(tokens[1])))
        elif command == 'Spacer':
            elements.append(
                MySpacer(adjustUnits(tokens[1]), adjustUnits(tokens[2])))
        elif command == 'Transition':
            elements.append(Transition(*tokens[1:]))
        elif command == 'SetPageCounter':
            elements.append(PageCounter(*tokens[1:]))
        else:
            log.error('Unknown command %s in raw pdf directive [%s]' %
                      (command, nodeid(node)))
    return elements
Example #21
0
    def __init__(
        self,
        filename,
        width=None,
        height=None,
        kind='direct',
        mask=None,
        lazy=True,
        srcinfo=None,
    ):
        client, uri = srcinfo
        cache = self.source_filecache.setdefault(client, {})
        pdffname = cache.get(filename)
        if pdffname is None:
            progname = shutil.which('inkscape')
            tmpf, pdffname = tempfile.mkstemp(suffix='.pdf')
            os.close(tmpf)
            client.to_unlink.append(pdffname)
            cache[filename] = pdffname

            # which version of inkscape?
            cmd = [progname, '--version']
            exitcode, out, err = InkscapeImage.run_cmd(cmd)
            if out.startswith('Inkscape 0.'):
                # Inkscape 0.x uses -A
                cmd = [progname, os.path.abspath(filename), '-A', pdffname]
            else:
                # Inkscape 1.x uses --export-filename
                cmd = [
                    progname,
                    os.path.abspath(filename),
                    '--export-filename',
                    pdffname,
                ]

            try:
                result = subprocess.call(cmd)
                if result != 0:
                    log.error("Failed to run command: %s", ' '.join(cmd))
            except OSError:
                log.error("Failed to run command: %s", ' '.join(cmd))
                raise

            self.load_xobj((client, pdffname))

        pdfuri = uri.replace(filename, pdffname)
        pdfsrc = client, pdfuri
        VectorPdf.__init__(self, pdfuri, width, height, kind, mask, lazy,
                           pdfsrc)
Example #22
0
def parseRaw(data, node):
    """
    Parse and process a simple DSL to handle creation of flowables.

    Supported (can add others on request):

      * PageBreak
      * Spacer width, height
    """
    elements = []
    lines = data.splitlines()
    for line in lines:
        lexer = shlex.shlex(line)
        lexer.whitespace += ","
        tokens = list(lexer)
        if not tokens:
            continue  # Empty line
        command = tokens[0]
        if command == "PageBreak":
            if len(tokens) == 1:
                elements.append(MyPageBreak())
            else:
                elements.append(MyPageBreak(tokens[1]))
        elif command == "EvenPageBreak":
            if len(tokens) == 1:
                elements.append(MyPageBreak(breakTo="even"))
            else:
                elements.append(MyPageBreak(tokens[1], breakTo="even"))
        elif command == "OddPageBreak":
            if len(tokens) == 1:
                elements.append(MyPageBreak(breakTo="odd"))
            else:
                elements.append(MyPageBreak(tokens[1], breakTo="odd"))
        # TODO: Where does CondPageBreak come from?
        # elif command == 'FrameBreak':
        #     if len(tokens) == 1:
        #         elements.append(CondPageBreak(99999))
        #     else:
        #         elements.append(CondPageBreak(float(tokens[1])))
        elif command == "Spacer":
            elements.append(MySpacer(adjustUnits(tokens[1]), adjustUnits(tokens[2])))
        elif command == "Transition":
            elements.append(Transition(*tokens[1:]))
        elif command == "SetPageCounter":
            elements.append(PageCounter(*tokens[1:]))
        else:
            log.error("Unknown command %s in raw pdf directive [%s]" % (command, nodeid(node)))
    return elements
Example #23
0
 def raster(self, filename, client):
     """Returns a URI to a rasterized version of the image"""
     cache = self.source_filecache.setdefault(client, {})
     pngfname = cache.get(filename+'_raster')
     if pngfname is None:
         tmpf, pngfname = tempfile.mkstemp(suffix='.png')
         os.close(tmpf)
         client.to_unlink.append(pngfname)
         cache[filename+'_raster'] = pngfname
         cmd = [progname, os.path.abspath(filename), '-e', pngfname, '-d', str(client.def_dpi)]
         try:
             subprocess.call(cmd)
             return pngfname
         except OSError, e:
             log.error("Failed to run command: %s", ' '.join(cmd))
             raise
    def handle_style(self, chunk):
        """ Parse through the source until we find lines that are no longer indented,
            then pass our indented lines to the RSON parser.
        """
        self.changed = True
        if chunk:
            log.error(".. style:: does not recognize string %s" % repr(chunk))
            return

        mystyles = "\n".join(self.read_indented())
        if not mystyles:
            log.error("Empty .. style:: block found")
        try:
            styles = rson_loads(mystyles)
        except ValueError, e:  # Error parsing the JSON data
            log.critical('Error parsing stylesheet "%s": %s' % (mystyles, str(e)))
Example #25
0
 def raster(self, filename, client):
     """Returns a URI to a rasterized version of the image"""
     cache = self.source_filecache.setdefault(client, {})
     pngfname = cache.get(filename+'_raster')
     if pngfname is None:
         tmpf, pngfname = tempfile.mkstemp(suffix='.png')
         os.close(tmpf)
         client.to_unlink.append(pngfname)
         cache[filename+'_raster'] = pngfname
         cmd = [progname, os.path.abspath(filename), '-e', pngfname, '-d', str(client.def_dpi)]
         try:
             subprocess.call(cmd)
             return pngfname
         except OSError, e:
             log.error("Failed to run command: %s", ' '.join(cmd))
             raise
    def handle_style(self, chunk):
        ''' Parse through the source until we find lines that are no longer indented,
            then pass our indented lines to the RSON parser.
        '''
        self.changed = True
        if chunk:
            log.error(".. style:: does not recognize string %s" % repr(chunk))
            return

        mystyles = '\n'.join(self.read_indented())
        if not mystyles:
            log.error("Empty .. style:: block found")
        try:
            styles = rson_loads(mystyles)
        except ValueError, e:  # Error parsing the JSON data
            log.critical('Error parsing stylesheet "%s": %s'%\
                (mystyles, str(e)))
Example #27
0
 def __init__(self, filename, width=None, height=None, kind='direct',
                              mask=None, lazy=True, srcinfo=None):
     client, uri = srcinfo
     cache = self.source_filecache.setdefault(client, {})
     pdffname = cache.get(filename)
     if pdffname is None:
         tmpf, pdffname = tempfile.mkstemp(suffix='.pdf')
         os.close(tmpf)
         client.to_unlink.append(pdffname)
         cache[filename] = pdffname
         cmd = [progname, os.path.abspath(filename), '-A', pdffname]
         try:
             subprocess.call(cmd)
         except OSError, e:
             log.error("Failed to run command: %s", ' '.join(cmd))
             raise
         self.load_xobj((client, pdffname))
Example #28
0
def adjustUnits(v, total=None, dpi=300, default_unit='pt', emsize=10):
    """
    Take something like 2cm and returns 2*cm.

    If you use % as a unit, it returns the percentage of "total".

    If total is not given, returns a percentage of the page width.
    However, if you get to that stage, you are doing it wrong.

    Example::

        >>> adjustUnits('50%', 200)
        100
    """
    if v is None or v == "":
        return None

    v = str(v)
    l = re.split(r'(-?[0-9.]*)', v)
    n = l[1]
    u = default_unit
    if len(l) == 3 and l[2]:
        u = l[2]
    if u in units.__dict__:
        return float(n) * units.__dict__[u]
    else:
        if u == '%':
            return float(n) * total / 100
        elif u == 'px':
            return float(n) * units.inch / dpi
        elif u == 'pt':
            return float(n)
        elif u == 'in':
            return float(n) * units.inch
        elif u == 'em':
            return float(n) * emsize
        elif u == 'ex':
            return float(n) * emsize / 2
        elif u == 'pc':  # picas!
            return float(n) * 12
        log.error('Unknown unit "%s"' % u)
    return float(n)
Example #29
0
def adjustUnits(v, total=None, dpi=300, default_unit='pt', emsize=10):
    """
    Take something like 2cm and returns 2*cm.

    If you use % as a unit, it returns the percentage of "total".

    If total is not given, returns a percentage of the page width.
    However, if you get to that stage, you are doing it wrong.

    Example::

        >>> adjustUnits('50%', 200)
        100
    """
    if v is None or v == "":
        return None

    v = str(v)
    l = re.split(r'(-?[0-9.]*)', v)
    n = l[1]
    u = default_unit
    if len(l) == 3 and l[2]:
        u = l[2]
    if u in units.__dict__:
        return float(n) * units.__dict__[u]
    else:
        if u == '%':
            return float(n) * total / 100
        elif u == 'px':
            return float(n) * units.inch / dpi
        elif u == 'pt':
            return float(n)
        elif u == 'in':
            return float(n) * units.inch
        elif u == 'em':
            return float(n) * emsize
        elif u == 'ex':
            return float(n) * emsize / 2
        elif u == 'pc':  # picas!
            return float(n) * 12
        log.error('Unknown unit "%s"' % u)
    return float(n)
Example #30
0
def init_math(app):
    """
        This is a dummy math extension.

        It's a hack, but if you want math in a PDF via pdfbuilder, and don't want to
        enable pngmath or jsmath, then enable this one.

        :copyright: Copyright 2007-2009 by the Sphinx team, see AUTHORS.
        :license: BSD, see LICENSE for details.
    """
    from sphinx.errors import SphinxError
    try:
        # Sphinx 0.6.4 and later
        from sphinx.ext.mathbase import setup_math as mathbase_setup
    except ImportError:
        try:
            # Sphinx 0.6.3
            from sphinx.ext.mathbase import setup as mathbase_setup
        except ImportError, e:
            log.error('Error importing sphinx math extension: %s', e)
def init_math(app):
    """
        This is a dummy math extension.

        It's a hack, but if you want math in a PDF via pdfbuilder, and don't want to
        enable pngmath or jsmath, then enable this one.

        :copyright: Copyright 2007-2009 by the Sphinx team, see AUTHORS.
        :license: BSD, see LICENSE for details.
    """
    from sphinx.errors import SphinxError
    try:
        # Sphinx 0.6.4 and later
        from sphinx.ext.mathbase import setup_math as mathbase_setup
    except ImportError:
        try:
            # Sphinx 0.6.3
            from sphinx.ext.mathbase import setup as mathbase_setup
        except ImportError, e:
            log.error('Error importing sphinx math extension: %s', e)
Example #32
0
    def handle_include(self, fname):
        for prefix in ('', os.path.dirname(self.sourcef.name)):
            try:
                f = open(os.path.join(prefix, fname), 'rb')
            except IOError:
                continue
            else:
                break
        else:
            log.error("Could not find include file %s", fname)
            self.changed = True
            return

        inc = Preprocess(f, True)
        self.styles.update(inc.styles)
        if inc.changed:
            self.changed = True
            if not inc.keep:
                return
            fname = inc.result.fname
        self.result.extend(['', '', '.. include:: ' + fname, ''])
Example #33
0
    def __init__(self, source):
        """Procesa el fichero linea a linea"""
        list.__init__(self)
        self.name = source.name
        self.changed = False

        for line in source.readlines():
            line = line.rstrip()
            # Si parece que empieza una lista...
            if line.startswith("- "):
                self.checkList(line)
            # Si parece que empieza una cabecera de primer nivel...
            elif line.startswith("="):
                self.checkHead(line)
            # El resto de lineas simplemente las añadimos al buffer.
            self.append(line)

        if self.changed:
            try:
                self.name = source.name + ".tmp"
                with open(self.name, "wb") as out:
                    out.write(self.read())
            except IOError:
                log.error("Could not save tmp file %s" % self.name)
Example #34
0
def validateCommands(commands):
    """
    Given a list of reportlab's table commands, it fixes some common errors
    and/or removes commands that can't be fixed
    """
    fixed = []

    for command in commands:
        command[0] = command[0].upper()
        flag = False
        # See if the command is valid
        if command[0] not in validCommands:
            log.error('Unknown table command %s in stylesheet', command[0])
            continue

        # See if start and stop are the right types
        if not isinstance(command[1], (list, tuple)):
            log.error(
                'Start cell in table command should be list or tuple, ' +
                'got %s [%s]', type(command[1]), command[1])
            flag = True

        if not isinstance(command[2], (list, tuple)):
            log.error(
                'Stop cell in table command should be list or tuple, ' +
                'got %s [%s]', type(command[1]), command[1])
            flag = True

        # See if the number of arguments is right
        l = len(command) - 3
        if l > validCommands[command[0]][1]:
            log.error('Too many arguments in table command: %s', command)
            flag = True

        if l < validCommands[command[0]][0]:
            log.error('Too few arguments in table command: %s', command)
            flag = True

        # Validate argument types
        for pos, arg in enumerate(command[3:]):
            typ = validCommands[command[0]][pos + 2]
            if typ == "color":
                # Convert all 'string' colors to numeric
                command[3 + pos] = formatColor(arg)
            elif typ == "colorlist":
                command[3 + pos] = [formatColor(c) for c in arg]
            elif typ == "number":
                pass
            elif typ == "string":
                # Force string, not unicode
                command[3 + pos] = str(arg)
            else:
                log.error("This should never happen: wrong type %s", typ)

        if not flag:
            fixed.append(command)

    return fixed
Example #35
0
    def size_for_node(self, node, client):
        """
        Given a docutils image node, return the size the image should have
        in the PDF document, and what 'kind' of size that is.
        That involves lots of guesswork.
        """
        uri = str(node.get("uri"))
        if uri.split("://")[0].lower() not in ('http', 'ftp', 'https'):
            uri = os.path.join(client.basedir, uri)
        else:
            uri, _ = urllib.request.urlretrieve(uri)
            client.to_unlink.append(uri)

        srcinfo = client, uri
        # Extract all the information from the URI
        imgname, extension, options = self.split_uri(uri)

        if not os.path.isfile(imgname):
            imgname = missing

        scale = float(node.get('scale', 100)) / 100

        # Figuring out the size to display of an image is ... annoying.
        # If the user provides a size with a unit, it's simple, adjustUnits
        # will return it in points and we're done.

        # However, often the unit wil be "%" (specially if it's meant for
        # HTML originally. In which case, we will use a percentage of
        # the containing frame.

        # Find the image size in pixels:
        kind = 'direct'
        xdpi, ydpi = client.styles.def_dpi, client.styles.def_dpi
        extension = imgname.split('.')[-1].lower()
        if extension in ['svg', 'svgz']:
            iw, ih = SVGImage(imgname, srcinfo=srcinfo).wrap(0, 0)
            # These are in pt, so convert to px
            iw = iw * xdpi / 72
            ih = ih * ydpi / 72

        elif extension == 'pdf':
            if VectorPdf is not None:
                xobj = VectorPdf.load_xobj(srcinfo)
                iw, ih = xobj.w, xobj.h
            else:
                pdf = LazyImports.pdfinfo
                if pdf is None:
                    log.warning(
                        'PDF images are not supported without pyPdf or pdfrw [%s]',
                        nodeid(node))
                    return 0, 0, 'direct'
                reader = pdf.PdfFileReader(open(imgname, 'rb'))
                box = [float(x) for x in reader.getPage(0)['/MediaBox']]
                iw, ih = x2 - x1, y2 - y1
            # These are in pt, so convert to px
            iw = iw * xdpi / 72.0
            ih = ih * ydpi / 72.0

        else:
            keeptrying = True
            if LazyImports.PILImage:
                try:
                    img = LazyImports.PILImage.open(imgname)
                    img.load()
                    iw, ih = img.size
                    xdpi, ydpi = img.info.get('dpi', (xdpi, ydpi))
                    keeptrying = False
                except IOError:  # PIL throws this when it's a broken/unknown image
                    pass
            if keeptrying and LazyImports.PMImage:
                img = LazyImports.PMImage(imgname)
                iw = img.size().width()
                ih = img.size().height()
                density = img.density()
                # The density is in pixelspercentimeter (!?)
                xdpi = density.width() * 2.54
                ydpi = density.height() * 2.54
                keeptrying = False
            if keeptrying:
                if extension not in ['jpg', 'jpeg']:
                    log.error(
                        "The image (%s, %s) is broken or in an unknown format",
                        imgname, nodeid(node))
                    raise ValueError
                else:
                    # Can be handled by reportlab
                    log.warning(
                        "Can't figure out size of the image (%s, %s). Install PIL for better results.",
                        imgname, nodeid(node))
                    iw = 1000
                    ih = 1000

        # Try to get the print resolution from the image itself via PIL.
        # If it fails, assume a DPI of 300, which is pretty much made up,
        # and then a 100% size would be iw*inch/300, so we pass
        # that as the second parameter to adjustUnits
        #
        # Some say the default DPI should be 72. That would mean
        # the largest printable image in A4 paper would be something
        # like 480x640. That would be awful.
        #

        w = node.get('width')
        h = node.get('height')
        if h is None and w is None:  # Nothing specified
            # Guess from iw, ih
            log.debug(
                "Using image %s without specifying size."
                "Calculating based on image size at %ddpi [%s]", imgname, xdpi,
                nodeid(node))
            w = iw * inch / xdpi
            h = ih * inch / ydpi
        elif w is not None:
            # Node specifies only w
            # In this particular case, we want the default unit
            # to be pixels so we work like rst2html
            if w[-1] == '%':
                kind = 'percentage_of_container'
                w = int(w[:-1])
            else:
                # This uses default DPI setting because we
                # are not using the image's "natural size"
                # this is what LaTeX does, according to the
                # docutils mailing list discussion
                w = client.styles.adjustUnits(w,
                                              client.styles.tw,
                                              default_unit='px')

            if h is None:
                # h is set from w with right aspect ratio
                h = w * ih / iw
            else:
                h = client.styles.adjustUnits(h,
                                              ih * inch / ydpi,
                                              default_unit='px')
        elif h is not None and w is None:
            if h[-1] != '%':
                h = client.styles.adjustUnits(h,
                                              ih * inch / ydpi,
                                              default_unit='px')

                # w is set from h with right aspect ratio
                w = h * iw / ih
            else:
                log.error(
                    'Setting height as a percentage does **not** work. ' +
                    'ignoring height parameter [%s]', nodeid(node))
                # Set both from image data
                w = iw * inch / xdpi
                h = ih * inch / ydpi

        # Apply scale factor
        w = w * scale
        h = h * scale

        # And now we have this probably completely bogus size!
        log.info("Image %s size calculated:  %fcm by %fcm [%s]", imgname,
                 w / cm, h / cm, nodeid(node))

        return w, h, kind
Example #36
0
def validateCommands(commands):
    """
    Given a list of reportlab's table commands, it fixes some common errors
    and/or removes commands that can't be fixed
    """
    fixed = []

    for command in commands:
        command[0] = command[0].upper()
        flag = False
        # See if the command is valid
        if command[0] not in validCommands:
            log.error('Unknown table command %s in stylesheet', command[0])
            continue

        # See if start and stop are the right types
        if not isinstance(command[1], (list, tuple)):
            log.error('Start cell in table command should be list or tuple, ' +
                      'got %s [%s]', type(command[1]), command[1])
            flag = True

        if not isinstance(command[2], (list, tuple)):
            log.error('Stop cell in table command should be list or tuple, ' +
                      'got %s [%s]', type(command[1]), command[1])
            flag = True

        # See if the number of arguments is right
        l = len(command) - 3
        if l > validCommands[command[0]][1]:
            log.error('Too many arguments in table command: %s', command)
            flag = True

        if l < validCommands[command[0]][0]:
            log.error('Too few arguments in table command: %s', command)
            flag = True

        # Validate argument types
        for pos, arg in enumerate(command[3:]):
            typ = validCommands[command[0]][pos + 2]
            if typ == "color":
                # Convert all 'string' colors to numeric
                command[3 + pos] = formatColor(arg)
            elif typ == "colorlist":
                command[3 + pos] = [formatColor(c) for c in arg]
            elif typ == "number":
                pass
            elif typ == "string":
                # Force string, not unicode
                command[3 + pos] = str(arg)
            else:
                log.error("This should never happen: wrong type %s", typ)

        if not flag:
            fixed.append(command)

    return fixed
Example #37
0
    def __init__(self, flist, font_path=None, style_path=None, def_dpi=300):
        log.info('Using stylesheets: %s' % ','.join(flist))
        # find base path
        if hasattr(sys, 'frozen'):
            self.PATH = abspath(dirname(sys.executable))
        else:
            self.PATH = abspath(dirname(__file__))

        # flist is a list of stylesheet filenames.
        # They will be loaded and merged in order.
        # but the two default stylesheets will always
        # be loaded first
        flist = [join(self.PATH, 'styles', 'styles.style'),
                 join(self.PATH, 'styles', 'default.style')] + flist

        self.def_dpi = def_dpi
        if font_path is None:
            font_path = []
        font_path += ['.', os.path.join(self.PATH, 'fonts')]
        self.FontSearchPath = [os.path.expanduser(p) for p in font_path]

        if style_path is None:
            style_path = []
        style_path += ['.', os.path.join(self.PATH, 'styles'),
                       '~/.rst2pdf/styles']
        self.StyleSearchPath = [os.path.expanduser(p) for p in style_path]
        self.FontSearchPath = list(set(self.FontSearchPath))
        self.StyleSearchPath = list(set(self.StyleSearchPath))

        log.info('FontPath:%s' % self.FontSearchPath)
        log.info('StylePath:%s' % self.StyleSearchPath)

        findfonts.flist = self.FontSearchPath
        # Page width, height
        self.pw = 0
        self.ph = 0

        # Page size [w,h]
        self.ps = None

        # Margins (top,bottom,left,right,gutter)
        self.tm = 0
        self.bm = 0
        self.lm = 0
        self.rm = 0
        self.gm = 0

        # text width
        self.tw = 0

        # Default emsize, later it will be the fontSize of the base style
        self.emsize = 10

        self.languages = []

        ssdata = self.readSheets(flist)

        # Get pageSetup data from all stylessheets in order:
        self.ps = pagesizes.A4
        self.page = {}
        for data, ssname in ssdata:
            page = data.get('pageSetup', {})
            if page:
                self.page.update(page)
                pgs = page.get('size', None)
                if pgs:  # A standard size
                    pgs = pgs.upper()
                    if pgs in pagesizes.__dict__:
                        self.ps = list(pagesizes.__dict__[pgs])
                        self.psname = pgs
                        if 'width' in self.page:
                            del(self.page['width'])
                        if 'height' in self.page:
                            del(self.page['height'])
                    elif pgs.endswith('-LANDSCAPE'):
                        self.psname = pgs.split('-')[0]
                        self.ps = list(pagesizes.landscape(pagesizes.__dict__[self.psname]))
                        if 'width' in self.page:
                            del(self.page['width'])
                        if 'height' in self.page:
                            del(self.page['height'])
                    else:
                        log.critical('Unknown page size %s in stylesheet %s' %
                            (page['size'], ssname))
                        continue
                else:  # A custom size
                    if 'size'in self.page:
                        del(self.page['size'])
                    # The sizes are expressed in some unit.
                    # For example, 2cm is 2 centimeters, and we need
                    # to do 2*cm (cm comes from reportlab.lib.units)
                    if 'width' in page:
                        self.ps[0] = self.adjustUnits(page['width'])
                    if 'height' in page:
                        self.ps[1] = self.adjustUnits(page['height'])
                self.pw, self.ph = self.ps
                if 'margin-left' in page:
                    self.lm = self.adjustUnits(page['margin-left'])
                if 'margin-right' in page:
                    self.rm = self.adjustUnits(page['margin-right'])
                if 'margin-top' in page:
                    self.tm = self.adjustUnits(page['margin-top'])
                if 'margin-bottom' in page:
                    self.bm = self.adjustUnits(page['margin-bottom'])
                if 'margin-gutter' in page:
                    self.gm = self.adjustUnits(page['margin-gutter'])
                if 'spacing-header' in page:
                    self.ts = self.adjustUnits(page['spacing-header'])
                if 'spacing-footer' in page:
                    self.bs = self.adjustUnits(page['spacing-footer'])
                if 'firstTemplate' in page:
                    self.firstTemplate = page['firstTemplate']

                # tw is the text width.
                # We need it to calculate header-footer height
                # and compress literal blocks.
                self.tw = self.pw - self.lm - self.rm - self.gm

        # Get page templates from all stylesheets
        self.pageTemplates = {}
        for data, ssname in ssdata:
            templates = data.get('pageTemplates', {})
            # templates is a dictionary of pageTemplates
            for key in templates:
                template = templates[key]
                # template is a dict.
                # template[´frames'] is a list of frames
                if key in self.pageTemplates:
                    self.pageTemplates[key].update(template)
                else:
                    self.pageTemplates[key] = template

        # Get font aliases from all stylesheets in order
        self.fontsAlias = {}
        for data, ssname in ssdata:
            self.fontsAlias.update(data.get('fontsAlias', {}))

        embedded_fontnames = []
        self.embedded = []
        # Embed all fonts indicated in all stylesheets
        for data, ssname in ssdata:
            embedded = data.get('embeddedFonts', [])

            for font in embedded:
                try:
                    # Just a font name, try to embed it
                    if isinstance(font, str):
                        # See if we can find the font
                        fname, pos = findfonts.guessFont(font)
                        if font in embedded_fontnames:
                            pass
                        else:
                            fontList = findfonts.autoEmbed(font)
                            if fontList:
                                embedded_fontnames.append(font)
                        if not fontList:
                            if (fname, pos) in embedded_fontnames:
                                fontList = None
                            else:
                                fontList = findfonts.autoEmbed(fname)
                        if fontList is not None:
                            self.embedded += fontList
                            # Maybe the font we got is not called
                            # the same as the one we gave
                            # so check that out
                            suff = ["", "-Oblique", "-Bold", "-BoldOblique"]
                            if not fontList[0].startswith(font):
                                # We need to create font aliases, and use them
                                for fname, aliasname in zip(
                                        fontList,
                                        [font + suffix for suffix in suff]):
                                    self.fontsAlias[aliasname] = fname
                        continue

                    # Each "font" is a list of four files, which will be
                    # used for regular / bold / italic / bold+italic
                    # versions of the font.
                    # If your font doesn't have one of them, just repeat
                    # the regular font.

                    # Example, using the Tuffy font from
                    # http://tulrich.com/fonts/
                    # "embeddedFonts" : [
                    #                    ["Tuffy.ttf",
                    #                     "Tuffy_Bold.ttf",
                    #                     "Tuffy_Italic.ttf",
                    #                     "Tuffy_Bold_Italic.ttf"]
                    #                   ],

                    # The fonts will be registered with the file name,
                    # minus the extension.

                    if font[0].lower().endswith('.ttf'):  # A True Type font
                        for variant in font:
                            location = self.findFont(variant)
                            pdfmetrics.registerFont(
                                TTFont(str(variant.split('.')[0]), location))
                            log.info('Registering font: %s from %s' %
                                     (str(variant.split('.')[0]), location))
                            self.embedded.append(str(variant.split('.')[0]))

                        # And map them all together
                        regular, bold, italic, bolditalic = [
                            variant.split('.')[0] for variant in font]
                        addMapping(regular, 0, 0, regular)
                        addMapping(regular, 0, 1, italic)
                        addMapping(regular, 1, 0, bold)
                        addMapping(regular, 1, 1, bolditalic)
                    else:  # A Type 1 font
                        # For type 1 fonts we require
                        # [FontName,regular,italic,bold,bolditalic]
                        # where each variant is a (pfbfile,afmfile) pair.
                        # For example, for the URW palladio from TeX:
                        # ["Palatino",("uplr8a.pfb","uplr8a.afm"),
                        #             ("uplri8a.pfb","uplri8a.afm"),
                        #             ("uplb8a.pfb","uplb8a.afm"),
                        #             ("uplbi8a.pfb","uplbi8a.afm")]
                        regular = pdfmetrics.EmbeddedType1Face(*font[1])
                        italic = pdfmetrics.EmbeddedType1Face(*font[2])
                        bold = pdfmetrics.EmbeddedType1Face(*font[3])
                        bolditalic = pdfmetrics.EmbeddedType1Face(*font[4])

                except Exception as e:
                    try:
                        if isinstance(font, list):
                            fname = font[0]
                        else:
                            fname = font
                        log.error("Error processing font %s: %s",
                                  os.path.splitext(fname)[0], str(e))
                        log.error("Registering %s as Helvetica alias", fname)
                        self.fontsAlias[fname] = 'Helvetica'
                    except Exception as e:
                        log.critical("Error processing font %s: %s",
                                     fname, str(e))
                        continue

        # Go though all styles in all stylesheets and find all fontNames.
        # Then decide what to do with them
        for data, ssname in ssdata:
            for [skey, style] in self.stylepairs(data):
                for key in style:
                    if key == 'fontName' or key.endswith('FontName'):
                        # It's an alias, replace it
                        if style[key] in self.fontsAlias:
                            style[key] = self.fontsAlias[style[key]]
                        # Embedded already, nothing to do
                        if style[key] in self.embedded:
                            continue
                        # Standard font, nothing to do
                        if style[key] in (
                            "Courier",
                            "Courier-Bold",
                            "Courier-BoldOblique",
                            "Courier-Oblique",
                            "Helvetica",
                            "Helvetica-Bold",
                            "Helvetica-BoldOblique",
                            "Helvetica-Oblique",
                            "Symbol",
                            "Times-Bold",
                            "Times-BoldItalic",
                            "Times-Italic",
                            "Times-Roman",
                            "ZapfDingbats"
                        ):
                            continue
                        # Now we need to do something
                        # See if we can find the font
                        fname, pos = findfonts.guessFont(style[key])

                        if style[key] in embedded_fontnames:
                            pass
                        else:
                            fontList = findfonts.autoEmbed(style[key])
                            if fontList:
                                embedded_fontnames.append(style[key])
                        if not fontList:
                            if (fname, pos) in embedded_fontnames:
                                fontList = None
                            else:
                                fontList = findfonts.autoEmbed(fname)
                            if fontList:
                                embedded_fontnames.append((fname, pos))
                        if fontList:
                            self.embedded += fontList
                            # Maybe the font we got is not called
                            # the same as the one we gave so check that out
                            suff = ["", "-Bold", "-Oblique", "-BoldOblique"]
                            if not fontList[0].startswith(style[key]):
                                # We need to create font aliases, and use them
                                basefname = style[key].split('-')[0]
                                for fname, aliasname in zip(
                                    fontList,
                                    [basefname + suffix for suffix in suff]
                                ):
                                    self.fontsAlias[aliasname] = fname
                                style[key] = self.fontsAlias[basefname +
                                                             suff[pos]]
                        else:
                            log.error('Unknown font: "%s",'
                                      "replacing with Helvetica", style[key])
                            style[key] = "Helvetica"

        # log.info('FontList: %s'%self.embedded)
        # log.info('FontAlias: %s'%self.fontsAlias)
        # Get styles from all stylesheets in order
        self.stylesheet = {}
        self.styles = []
        self.linkColor = 'navy'
        # FIXME: linkColor should probably not be a global
        #        style, and tocColor should probably not
        #        be a special case, but for now I'm going
        #        with the flow...
        self.tocColor = None
        for data, ssname in ssdata:
            self.linkColor = data.get('linkColor') or self.linkColor
            self.tocColor = data.get('tocColor') or self.tocColor
            for [skey, style] in self.stylepairs(data):
                sdict = {}
                # FIXME: this is done completely backwards
                for key in style:
                    # Handle color references by name
                    if key == 'color' or key.endswith('Color') and style[key]:
                        style[key] = formatColor(style[key])

                    # Yet another workaround for the unicode bug in
                    # reportlab's toColor
                    elif key == 'commands':
                        style[key] = validateCommands(style[key])
                        # for command in style[key]:
                            # c=command[0].upper()
                            # if c=='ROWBACKGROUNDS':
                                # command[3]=[str(c) for c in command[3]]
                            # elif c in ['BOX','INNERGRID'] or c.startswith('LINE'):
                                # command[4]=str(command[4])

                    # Handle alignment constants
                    elif key == 'alignment':
                        style[key] = dict(TA_LEFT=0,
                                          LEFT=0,
                                          TA_CENTER=1,
                                          CENTER=1,
                                          TA_CENTRE=1,
                                          CENTRE=1,
                                          TA_RIGHT=2,
                                          RIGHT=2,
                                          TA_JUSTIFY=4,
                                          JUSTIFY=4,
                                          DECIMAL=8,)[style[key].upper()]

                    elif key == 'language':
                        if not style[key] in self.languages:
                            self.languages.append(style[key])

                    # Make keys str instead of unicode (required by reportlab)
                    sdict[str(key)] = style[key]
                    sdict['name'] = skey
                # If the style already exists, update it
                if skey in self.stylesheet:
                    self.stylesheet[skey].update(sdict)
                else:  # New style
                    self.stylesheet[skey] = sdict
                    self.styles.append(sdict)

        # If the stylesheet has a style name docutils won't reach
        # make a copy with a sanitized name.
        # This may make name collisions possible but that should be
        # rare (who would have custom_name and custom-name in the
        # same stylesheet? ;-)
        # Issue 339

        styles2 = []
        for s in self.styles:
            if not re.match("^[a-z](-?[a-z0-9]+)*$", s['name']):
                s2 = copy.copy(s)
                s2['name'] = docutils.nodes.make_id(s['name'])
                log.warning(('%s is an invalid docutils class name, adding ' +
                             'alias %s') % (s['name'], s2['name']))
                styles2.append(s2)
        self.styles.extend(styles2)

        # And create  reportlabs stylesheet
        self.StyleSheet = StyleSheet1()
        # Patch to make the code compatible with reportlab from SVN 2.4+ and
        # 2.4
        if not hasattr(self.StyleSheet, 'has_key'):
            self.StyleSheet.__class__.has_key = lambda s, k: k in s
        for s in self.styles:
            if 'parent' in s:
                if s['parent'] is None:
                    if s['name'] != 'base':
                        s['parent'] = self.StyleSheet['base']
                    else:
                        del(s['parent'])
                else:
                    s['parent'] = self.StyleSheet[s['parent']]
            else:
                if s['name'] != 'base':
                    s['parent'] = self.StyleSheet['base']

            # If the style has no bulletFontName but it has a fontName, set it
            if ('bulletFontName' not in s) and ('fontName' in s):
                s['bulletFontName'] = s['fontName']

            hasFS = True
            # Adjust fontsize units
            if 'fontSize' not in s:
                s['fontSize'] = s['parent'].fontSize
                s['trueFontSize'] = None
                hasFS = False
            elif 'parent' in s:
                # This means you can set the fontSize to
                # "2cm" or to "150%" which will be calculated
                # relative to the parent style
                s['fontSize'] = self.adjustUnits(s['fontSize'],
                                                 s['parent'].fontSize)
                s['trueFontSize'] = s['fontSize']
            else:
                # If s has no parent, it's base, which has
                # an explicit point size by default and %
                # makes no sense, but guess it as % of 10pt
                s['fontSize'] = self.adjustUnits(s['fontSize'], 10)

            # If the leading is not set, but the size is, set it
            if 'leading' not in s and hasFS:
                s['leading'] = 1.2 * s['fontSize']

            # If the bullet font size is not set, set it as fontSize
            if ('bulletFontSize' not in s) and ('fontSize' in s):
                s['bulletFontSize'] = s['fontSize']

            # If the borderPadding is a list and wordaxe <=0.3.2,
            # convert it to an integer. Workaround for Issue
            if (
                'borderPadding' in s and
                HAS_WORDAXE and
                wordaxe_version <= 'wordaxe 0.3.2' and
                isinstance(s['borderPadding'], list)
            ):
                log.warning(('Using a borderPadding list in style %s with ' +
                             'wordaxe <= 0.3.2. That is  not supported, so ' +
                             'it will probably look wrong') % s['name'])
                s['borderPadding'] = s['borderPadding'][0]

            self.StyleSheet.add(ParagraphStyle(**s))

        self.emsize = self['base'].fontSize
        # Make stdFont the basefont, for Issue 65
        reportlab.rl_config.canvas_basefontname = self['base'].fontName
        # Make stdFont the default font for table cell styles (Issue 65)
        reportlab.platypus.tables.CellStyle.fontname = self['base'].fontName
Example #38
0
def findTTFont(fname):
    def get_family(query):
        data = make_string(subprocess.check_output(["fc-match", query]))
        for line in data.splitlines():
            line = line.strip()
            if not line:
                continue
            family = line.split('"')[1].replace('"', "")
            if family:
                return family
        return None

    def get_fname(query):
        data = make_string(subprocess.check_output(["fc-match", "-v", query]))
        for line in data.splitlines():
            line = line.strip()
            if line.startswith("file: "):
                return line.split('"')[1]
        return None

    def get_variants(family):
        variants = [
            get_fname(family + ":style=Roman"),
            get_fname(family + ":style=Bold"),
            get_fname(family + ":style=Oblique"),
            get_fname(family + ":style=Bold Oblique"),
        ]
        if variants[2] == variants[0]:
            variants[2] = get_fname(family + ":style=Italic")
        if variants[3] == variants[0]:
            variants[3] = get_fname(family + ":style=Bold Italic")
        if variants[0].endswith(".pfb") or variants[0].endswith(".gz"):
            return None
        return variants

    if os.name != "nt":
        family = get_family(fname)
        if not family:
            log.error("Unknown font: %s", fname)
            return None
        return get_variants(family)
    else:
        # lookup required font in registry lookup, alternative approach
        # is to let loadFont() traverse windows font directory or use
        # ctypes with EnumFontFamiliesEx

        def get_nt_fname(ftname):
            import winreg as _w

            fontkey = _w.OpenKey(
                _w.HKEY_LOCAL_MACHINE,
                r"SOFTWARE\Microsoft\Windows NT\CurrentVersion\Fonts",
            )
            fontname = ftname + " (TrueType)"
            try:
                fname = _w.QueryValueEx(fontkey, fontname)[0]
                if os.path.isabs(fname):
                    fontkey.close()
                    return fname
                fontdir = os.environ.get("SystemRoot", "C:\\Windows")
                fontdir += "\\Fonts"
                fontkey.Close()
                return fontdir + "\\" + fname
            except WindowsError:
                fontkey.Close()
                return None

        family, pos = guessFont(fname)
        fontfile = get_nt_fname(fname)
        if not fontfile:
            if pos == 0:
                fontfile = get_nt_fname(family)
            elif pos == 1:
                fontfile = get_nt_fname(family + " Bold")
            elif pos == 2:
                fontfile = get_nt_fname(family + " Italic") or get_nt_fname(
                    family + " Oblique"
                )
            else:
                fontfile = get_nt_fname(family + " Bold Italic") or get_nt_fname(
                    family + " Bold Oblique"
                )

            if not fontfile:
                log.error("Unknown font: %s", fname)
                return None

        family, pos = guessFont(fname)
        variants = [
            get_nt_fname(family) or fontfile,
            get_nt_fname(family + " Bold") or fontfile,
            get_nt_fname(family + " Italic")
            or get_nt_fname(family + " Oblique")
            or fontfile,
            get_nt_fname(family + " Bold Italic")
            or get_nt_fname(family + " Bold Oblique")
            or fontfile,
        ]
        return variants
Example #39
0
def autoEmbed(fname):
    """
    Given a font name, do a best-effort of embedding the font and its variants.

    Return a list of the font names it registered with ReportLab.
    """
    log.info('Trying to embed %s' % fname)
    fontList = []
    variants = []
    font = findFont(fname)
    if font:  # We have this font located
        if font[0].lower()[-4:] == '.afm':  # Type 1 font
            family = families[font[2]]

            # Register the whole family of faces
            faces = [pdfmetrics.EmbeddedType1Face(*fonts[fn.lower()][:2])
                     for fn in family]
            for face in faces:
                pdfmetrics.registerTypeFace(face)

            for face, name in zip(faces, family):
                fontList.append(name)
                font = pdfmetrics.Font(face, name, "WinAnsiEncoding")
                log.info('Registering font: %s from %s' % (face, name))
                pdfmetrics.registerFont(font)

            # Map the variants
            regular, italic, bold, bolditalic = family
            addMapping(fname, 0, 0, regular)
            addMapping(fname, 0, 1, italic)
            addMapping(fname, 1, 0, bold)
            addMapping(fname, 1, 1, bolditalic)
            addMapping(regular, 0, 0, regular)
            addMapping(regular, 0, 1, italic)
            addMapping(regular, 1, 0, bold)
            addMapping(regular, 1, 1, bolditalic)
            log.info('Embedding as %s' % fontList)
            return fontList
        else:  # A TTF font
            variants = [fonts[f.lower()][0] for f in families[font[2]]]
    if not variants:  # Try fc-match
        variants = findTTFont(fname)
    # It is a TT Font and we found it using fc-match (or found *something*)
    if variants:
        for variant in variants:
            vname = os.path.basename(variant)[:-4]
            try:
                if vname not in pdfmetrics._fonts:
                    _font = TTFont(vname, variant)
                    log.info('Registering font: %s from %s' % (vname, variant))
                    pdfmetrics.registerFont(_font)
            except TTFError:
                log.error('Error registering font: %s from %s' % (vname, variant))
            else:
                fontList.append(vname)
        regular, bold, italic, bolditalic = [
            os.path.basename(variant)[:-4] for variant in variants]
        addMapping(regular, 0, 0, regular)
        addMapping(regular, 0, 1, italic)
        addMapping(regular, 1, 0, bold)
        addMapping(regular, 1, 1, bolditalic)
        log.info('Embedding via findTTFont as %s' % fontList)
    return fontList
Example #40
0
 def parseHTML(data, none):
     log.error("You need xhtml2pdf installed to use the raw HTML directive.")
     return []
Example #41
0
    def get_backend(self, uri, client):
        """
        Given the filename of an image, return (fname, backend).

        fname is the filename to be used (could be the same as filename,
        or something different if the image had to be converted or is
        missing), and backend is an Image class that can handle fname.

        If uri ends with '.*' then the returned filename will be the best
        quality supported at the moment.

        That means:  PDF > SVG > anything else
        """
        backend = defaultimage

        # Extract all the information from the URI
        filename, extension, options = self.split_uri(uri)

        if '*' in filename:
            preferred = ['gif', 'jpg', 'png', 'svg', 'pdf']

            # Find out what images are available
            available = glob.glob(filename)
            cfn = available[0]
            cv = -10
            for fn in available:
                ext = fn.split('.')[-1]
                if ext in preferred:
                    v = preferred.index(ext)
                else:
                    v = -1
                if v > cv:
                    cv = v
                    cfn = fn
            # cfn should have our favourite type of
            # those available
            filename = cfn
            extension = cfn.split('.')[-1]
            uri = filename

        # If the image doesn't exist, we use a 'missing' image
        if not os.path.exists(filename):
            log.error("Missing image file: %s", filename)
            filename = missing

        if extension in ['svg', 'svgz']:
            log.info('Backend for %s is SVGIMage' % filename)
            backend = SVGImage

        elif extension in ['pdf']:
            if VectorPdf is not None and filename is not missing:
                backend = VectorPdf
                filename = uri

            # PDF images are implemented by converting via PythonMagick
            # w,h are in pixels. I need to set the density
            # of the image to  the right dpi so this
            # looks decent
            elif LazyImports.PMImage or LazyImports.gfx:
                filename = self.raster(filename, client)
            else:
                log.warning(
                    'Minimal PDF image support requires ' +
                    'PythonMagick or the vectorpdf extension [%s]', filename)
                filename = missing
        elif extension != 'jpg' and not LazyImports.PILImage:
            if LazyImports.PMImage:
                # Need to convert to JPG via PythonMagick
                filename = self.raster(filename, client)
            else:
                # No way to make this work
                log.error('To use a %s image you need PIL installed [%s]',
                          extension, filename)
                filename = missing
        return filename, backend
Example #42
0
    def write(self, *ignored):

        self.init_document_data()

        if self.config.pdf_verbosity > 1:
            log.setLevel(logging.DEBUG)
        elif self.config.pdf_verbosity > 0:
            log.setLevel(logging.INFO)

        for entry in self.document_data:
            try:
                docname, targetname, title, author = entry[:4]
                # Custom options per document
                if len(entry)>4 and isinstance(entry[4],dict):
                    opts=entry[4]
                else:
                    opts={}
                self.info("processing " + targetname + "... ", nonl=1)
                self.opts = opts
                class dummy:
                    extensions=self.config.pdf_extensions

                createpdf.add_extensions(dummy())

                self.page_template=opts.get('pdf_page_template',self.config.pdf_page_template)

                docwriter = PDFWriter(self,
                                stylesheets=opts.get('pdf_stylesheets',self.config.pdf_stylesheets),
                                language=opts.get('pdf_language',self.config.pdf_language),
                                breaklevel=opts.get('pdf_break_level',self.config.pdf_break_level),
                                breakside=opts.get('pdf_breakside',self.config.pdf_breakside),
                                fontpath=opts.get('pdf_font_path',self.config.pdf_font_path),
                                fitmode=opts.get('pdf_fit_mode',self.config.pdf_fit_mode),
                                compressed=opts.get('pdf_compressed',self.config.pdf_compressed),
                                inline_footnotes=opts.get('pdf_inline_footnotes',self.config.pdf_inline_footnotes),
                                splittables=opts.get('pdf_splittables',self.config.pdf_splittables),
                                default_dpi=opts.get('pdf_default_dpi',self.config.pdf_default_dpi),
                                page_template=self.page_template,
                                invariant=opts.get('pdf_invariant',self.config.pdf_invariant),
                                real_footnotes=opts.get('pdf_real_footnotes',self.config.pdf_real_footnotes),
                                use_toc=opts.get('pdf_use_toc',self.config.pdf_use_toc),
                                toc_depth=opts.get('pdf_toc_depth',self.config.pdf_toc_depth),
                                use_coverpage=opts.get('pdf_use_coverpage',self.config.pdf_use_coverpage),
                                use_numbered_links=opts.get('pdf_use_numbered_links',self.config.pdf_use_numbered_links),
                                fit_background_mode=opts.get('pdf_fit_background_mode',self.config.pdf_fit_background_mode),
                                baseurl=opts.get('pdf_baseurl',self.config.pdf_baseurl),
                                section_header_depth=opts.get('section_header_depth',self.config.section_header_depth),
                                srcdir=self.srcdir,
                                style_path=opts.get('pdf_style_path', self.config.pdf_style_path),
                                config=self.config,
                                )

                tgt_file = path.join(self.outdir, targetname + self.out_suffix)
                destination = FileOutput(destination=open(tgt_file,'wb'), encoding='utf-8')
                doctree = self.assemble_doctree(docname,title,author,
                    appendices=opts.get('pdf_appendices', self.config.pdf_appendices) or [])
                doctree.settings.author=author
                doctree.settings.title=title
                self.info("done")
                self.info("writing " + targetname + "... ", nonl=1)
                docwriter.write(doctree, destination)
                self.info("done")
            except Exception, e:
                log.error(str(e))
                print_exc()
                self.info(red("FAILED"))
Example #43
0
    def raster(self, filename, client):
        """
        Takes a filename and converts it to a raster image
        reportlab can process
        """
        if not os.path.exists(filename):
            log.error("Missing image file: %s", filename)
            return missing

        try:
            # First try to rasterize using the suggested backend
            backend = self.get_backend(filename, client)[1]
            return backend.raster(filename, client)
        except:
            pass

        # Last resort: try everything
        PILImage = LazyImports.PILImage

        if PILImage:
            ext = '.png'
        else:
            ext = '.jpg'

        extension = os.path.splitext(filename)[-1][1:].lower()

        if PILImage:  # See if pil can process it
            try:
                PILImage.open(filename)
                return filename
            except:
                # Can't read it
                pass

        # PIL can't or isn't here, so try with Magick
        PMImage = LazyImports.PMImage
        if PMImage:
            try:
                img = PMImage()
                # Adjust density to pixels/cm
                dpi = client.styles.def_dpi
                img.density("%sx%s" % (dpi, dpi))
                img.read(str(filename))
                _, tmpname = tempfile.mkstemp(suffix=ext)
                img.write(tmpname)
                client.to_unlink.append(tmpname)
                return tmpname
            except:
                # Magick couldn't
                pass
        elif PILImage:
            # Try to use gfx, which produces PNGs, and then
            # pass them through PIL.
            # This only really matters for PDFs but it's worth trying
            gfx = LazyImports.gfx
            try:
                # Need to convert the DPI to % where 100% is 72DPI
                gfx.setparameter("zoom", str(client.styles.def_dpi / .72))
                if extension == 'pdf':
                    doc = gfx.open("pdf", filename)
                elif extension == 'swf':
                    doc = gfx.open("swf", filename)
                else:
                    doc = None
                if doc:
                    img = gfx.ImageList()
                    img.setparameter("antialise", "1")  # turn on antialising
                    page = doc.getPage(1)
                    img.startpage(page.width, page.height)
                    page.render(img)
                    img.endpage()
                    _, tmpname = tempfile.mkstemp(suffix='.png')
                    img.save(tmpname)
                    client.to_unlink.append(tmpname)
                    return tmpname
            except:  # Didn't work
                pass

        # PIL can't and Magick can't, so we can't
        self.support_warning()
        log.error("Couldn't load image [%s]" % filename)
        return missing
Example #44
0
    def size_for_node(self, node, client):
        """
        Given a docutils image node, return the size the image should have
        in the PDF document, and what 'kind' of size that is.
        That involves lots of guesswork.
        """
        uri = str(node.get("uri"))
        if uri.split("://")[0].lower() not in ('http', 'ftp', 'https'):
            uri = os.path.join(client.basedir, uri)
        else:
            uri, _ = urllib.request.urlretrieve(uri)
            client.to_unlink.append(uri)

        srcinfo = client, uri
        # Extract all the information from the URI
        imgname, extension, options = self.split_uri(uri)

        if not os.path.isfile(imgname):
            imgname = missing

        scale = float(node.get('scale', 100)) / 100

        # Figuring out the size to display of an image is ... annoying.
        # If the user provides a size with a unit, it's simple, adjustUnits
        # will return it in points and we're done.

        # However, often the unit wil be "%" (specially if it's meant for
        # HTML originally. In which case, we will use a percentage of
        # the containing frame.

        # Find the image size in pixels:
        kind = 'direct'
        xdpi, ydpi = client.styles.def_dpi, client.styles.def_dpi
        extension = imgname.split('.')[-1].lower()
        if extension in ['svg', 'svgz']:
            iw, ih = SVGImage(imgname, srcinfo=srcinfo).wrap(0, 0)
            # These are in pt, so convert to px
            iw = iw * xdpi / 72
            ih = ih * ydpi / 72

        elif extension == 'pdf':
            if VectorPdf is not None:
                xobj = VectorPdf.load_xobj(srcinfo)
                iw, ih = xobj.w, xobj.h
            else:
                pdf = LazyImports.pdfinfo
                if pdf is None:
                    log.warning('PDF images are not supported without pyPdf or pdfrw [%s]', nodeid(node))
                    return 0, 0, 'direct'
                reader = pdf.PdfFileReader(open(imgname, 'rb'))
                box = [float(x) for x in reader.getPage(0)['/MediaBox']]
                iw, ih = x2 - x1, y2 - y1
            # These are in pt, so convert to px
            iw = iw * xdpi / 72.0
            ih = ih * ydpi / 72.0

        else:
            keeptrying = True
            if LazyImports.PILImage:
                try:
                    img = LazyImports.PILImage.open(imgname)
                    img.load()
                    iw, ih = img.size
                    xdpi, ydpi = img.info.get('dpi', (xdpi, ydpi))
                    keeptrying = False
                except IOError:  # PIL throws this when it's a broken/unknown image
                    pass
            if keeptrying and LazyImports.PMImage:
                img = LazyImports.PMImage(imgname)
                iw = img.size().width()
                ih = img.size().height()
                density = img.density()
                # The density is in pixelspercentimeter (!?)
                xdpi = density.width() * 2.54
                ydpi = density.height() * 2.54
                keeptrying = False
            if keeptrying:
                if extension not in ['jpg', 'jpeg']:
                    log.error("The image (%s, %s) is broken or in an unknown format"
                                , imgname, nodeid(node))
                    raise ValueError
                else:
                    # Can be handled by reportlab
                    log.warning("Can't figure out size of the image (%s, %s). Install PIL for better results."
                                , imgname, nodeid(node))
                    iw = 1000
                    ih = 1000

        # Try to get the print resolution from the image itself via PIL.
        # If it fails, assume a DPI of 300, which is pretty much made up,
        # and then a 100% size would be iw*inch/300, so we pass
        # that as the second parameter to adjustUnits
        #
        # Some say the default DPI should be 72. That would mean
        # the largest printable image in A4 paper would be something
        # like 480x640. That would be awful.
        #

        w = node.get('width')
        h = node.get('height')
        if h is None and w is None:  # Nothing specified
            # Guess from iw, ih
            log.debug("Using image %s without specifying size."
                      "Calculating based on image size at %ddpi [%s]",
                      imgname, xdpi, nodeid(node))
            w = iw * inch / xdpi
            h = ih * inch / ydpi
        elif w is not None:
            # Node specifies only w
            # In this particular case, we want the default unit
            # to be pixels so we work like rst2html
            if w[-1] == '%':
                kind = 'percentage_of_container'
                w = int(w[:-1])
            else:
                # This uses default DPI setting because we
                # are not using the image's "natural size"
                # this is what LaTeX does, according to the
                # docutils mailing list discussion
                w = client.styles.adjustUnits(w, client.styles.tw,
                                              default_unit='px')

            if h is None:
                # h is set from w with right aspect ratio
                h = w * ih / iw
            else:
                h = client.styles.adjustUnits(h, ih * inch / ydpi, default_unit='px')
        elif h is not None and w is None:
            if h[-1] != '%':
                h = client.styles.adjustUnits(h, ih * inch / ydpi, default_unit='px')

                # w is set from h with right aspect ratio
                w = h * iw / ih
            else:
                log.error('Setting height as a percentage does **not** work. ' +
                          'ignoring height parameter [%s]', nodeid(node))
                # Set both from image data
                w = iw * inch / xdpi
                h = ih * inch / ydpi

        # Apply scale factor
        w = w * scale
        h = h * scale

        # And now we have this probably completely bogus size!
        log.info("Image %s size calculated:  %fcm by %fcm [%s]",
                 imgname, w / cm, h / cm, nodeid(node))

        return w, h, kind
Example #45
0
    def raster(self, filename, client):
        """
        Takes a filename and converts it to a raster image
        reportlab can process
        """
        if not os.path.exists(filename):
            log.error("Missing image file: %s", filename)
            return missing

        try:
            # First try to rasterize using the suggested backend
            backend = self.get_backend(filename, client)[1]
            return backend.raster(filename, client)
        except:
            pass

        # Last resort: try everything
        PILImage = LazyImports.PILImage

        if PILImage:
            ext = '.png'
        else:
            ext = '.jpg'

        extension = os.path.splitext(filename)[-1][1:].lower()

        if PILImage:  # See if pil can process it
            try:
                PILImage.open(filename)
                return filename
            except:
                # Can't read it
                pass

        # PIL can't or isn't here, so try with Magick
        PMImage = LazyImports.PMImage
        if PMImage:
            try:
                img = PMImage()
                # Adjust density to pixels/cm
                dpi = client.styles.def_dpi
                img.density("%sx%s" % (dpi, dpi))
                img.read(str(filename))
                _, tmpname = tempfile.mkstemp(suffix=ext)
                img.write(tmpname)
                client.to_unlink.append(tmpname)
                return tmpname
            except:
                # Magick couldn't
                pass
        elif PILImage:
            # Try to use gfx, which produces PNGs, and then
            # pass them through PIL.
            # This only really matters for PDFs but it's worth trying
            gfx = LazyImports.gfx
            try:
                # Need to convert the DPI to % where 100% is 72DPI
                gfx.setparameter("zoom", str(client.styles.def_dpi / .72))
                if extension == 'pdf':
                    doc = gfx.open("pdf", filename)
                elif extension == 'swf':
                    doc = gfx.open("swf", filename)
                else:
                    doc = None
                if doc:
                    img = gfx.ImageList()
                    img.setparameter("antialise", "1")  # turn on antialising
                    page = doc.getPage(1)
                    img.startpage(page.width, page.height)
                    page.render(img)
                    img.endpage()
                    _, tmpname = tempfile.mkstemp(suffix='.png')
                    img.save(tmpname)
                    client.to_unlink.append(tmpname)
                    return tmpname
            except:  # Didn't work
                pass

        # PIL can't and Magick can't, so we can't
        self.support_warning()
        log.error("Couldn't load image [%s]" % filename)
        return missing
    def translate(self):
        visitor = PDFTranslator(self.document, self.builder)
        self.document.walkabout(visitor)
        lang = self.config.language or 'en'
        langmod = get_language_available(lang)[2]
        self.docutils_languages = {lang: langmod}

        # Generate Contents topic manually
        if self.use_toc:
            contents = nodes.topic(classes=['contents'])
            contents += nodes.title('')
            contents[0] += nodes.Text(langmod.labels['contents'])
            contents['ids'] = ['Contents']
            pending = nodes.topic()
            contents.append(pending)
            pending.details = {}
            self.document.insert(
                0, nodes.raw(text='SetPageCounter 1 arabic', format='pdf'))
            self.document.insert(
                0,
                nodes.raw(text='OddPageBreak %s' % self.page_template,
                          format='pdf'))
            self.document.insert(0, contents)
            self.document.insert(
                0, nodes.raw(text='SetPageCounter 1 lowerroman', format='pdf'))
            contTrans = PDFContents(self.document)
            contTrans.toc_depth = self.toc_depth
            contTrans.startnode = pending
            contTrans.apply()

        if self.use_coverpage:
            # Generate cover page

            # FIXME: duplicate from createpdf, refactor!

            # Find cover template, save it in cover_file
            def find_cover(name):
                cover_path = [
                    self.srcdir,
                    os.path.expanduser('~/.rst2pdf'),
                    os.path.join(self.PATH, 'templates')
                ]

                # Add the Sphinx template paths
                def add_template_path(path):
                    return os.path.join(self.srcdir, path)

                cover_path.extend(
                    map(add_template_path, self.config.templates_path))

                cover_file = None
                for d in cover_path:
                    if os.path.exists(os.path.join(d, name)):
                        cover_file = os.path.join(d, name)
                        break
                return cover_file

            cover_file = find_cover(self.config.pdf_cover_template)
            if cover_file is None:
                log.error("Can't find cover template %s, using default" %
                          self.custom_cover)
                cover_file = find_cover('sphinxcover.tmpl')

            # This is what's used in the python docs because
            # Latex does a manual linebreak. This sucks.
            authors = self.document.settings.author.split('\\')

            # Feed data to the template, get restructured text.
            cover_text = createpdf.renderTemplate(
                tname=cover_file,
                title=self.document.settings.title
                or visitor.elements['title'],
                subtitle='%s %s' % (_('version'), self.config.version),
                authors=authors,
                date=ustrftime(self.config.today_fmt or _('%B %d, %Y')))

            cover_tree = docutils.core.publish_doctree(cover_text)
            self.document.insert(0, cover_tree)

        sio = StringIO()

        if self.invariant:
            createpdf.patch_PDFDate()
            createpdf.patch_digester()

        createpdf.RstToPdf(sphinx=True,
                           stylesheets=self.stylesheets,
                           language=self.__language,
                           breaklevel=self.breaklevel,
                           breakside=self.breakside,
                           fit_mode=self.fitmode,
                           font_path=self.fontpath,
                           inline_footnotes=self.inline_footnotes,
                           highlightlang=self.highlightlang,
                           splittables=self.splittables,
                           style_path=self.style_path,
                           basedir=self.srcdir,
                           def_dpi=self.default_dpi,
                           real_footnotes=self.real_footnotes,
                           numbered_links=self.use_numbered_links,
                           background_fit_mode=self.fit_background_mode,
                           baseurl=self.baseurl,
                           section_header_depth=self.section_header_depth,
                           floating_images=self.floating_images).createPdf(
                               doctree=self.document,
                               output=sio,
                               compressed=self.compressed)
        self.output = sio.getvalue()
Example #47
0
def findTTFont(fname):
    def get_family(query):
        data = os.popen("fc-match \"%s\"" % query, "r").read()
        for line in data.splitlines():
            line = line.strip()
            if not line:
                continue
            fname, family, _, variant = line.split('"')[:4]
            family = family.replace('"', '')
            if family:
                return family
        return None

    def get_fname(query):
        data = os.popen("fc-match -v \"%s\"" % query, "r").read()
        for line in data.splitlines():
            line = line.strip()
            if line.startswith("file: "):
                return line.split('"')[1]
        return None

    def get_variants(family):
        variants = [
            get_fname(family + ":style=Roman"),
            get_fname(family + ":style=Bold"),
            get_fname(family + ":style=Oblique"),
            get_fname(family + ":style=Bold Oblique")]
        if variants[2] == variants[0]:
            variants[2] = get_fname(family + ":style=Italic")
        if variants[3] == variants[0]:
            variants[3] = get_fname(family + ":style=Bold Italic")
        if variants[0].endswith('.pfb') or variants[0].endswith('.gz'):
            return None
        return variants

    if os.name != 'nt':
        family = get_family(fname)
        if not family:
            log.error("Unknown font: %s", fname)
            return None
        return get_variants(family)
    else:
        # lookup required font in registry lookup, alternative approach
        # is to let loadFont() traverse windows font directory or use
        # ctypes with EnumFontFamiliesEx

        def get_nt_fname(ftname):
            import winreg as _w
            fontkey = _w.OpenKey(
                _w.HKEY_LOCAL_MACHINE,
                "SOFTWARE\Microsoft\Windows NT\CurrentVersion\Fonts"
            )
            fontname = ftname + " (TrueType)"
            try:
                fname = _w.QueryValueEx(fontkey, fontname)[0]
                if os.path.isabs(fname):
                    fontkey.close()
                    return fname
                fontdir = os.environ.get("SystemRoot", "C:\\Windows")
                fontdir += "\\Fonts"
                fontkey.Close()
                return fontdir + "\\" + fname
            except WindowsError:
                fontkey.Close()
                return None

        family, pos = guessFont(fname)
        fontfile = get_nt_fname(fname)
        if not fontfile:
            if pos == 0:
                fontfile = get_nt_fname(family)
            elif pos == 1:
                fontfile = get_nt_fname(family + " Bold")
            elif pos == 2:
                fontfile = get_nt_fname(family + " Italic") or \
                    get_nt_fname(family + " Oblique")
            else:
                fontfile = get_nt_fname(family + " Bold Italic") or \
                    get_nt_fname(family + " Bold Oblique")

            if not fontfile:
                log.error("Unknown font: %s", fname)
                return None

        family, pos = guessFont(fname)
        variants = [
            get_nt_fname(family) or fontfile,
            get_nt_fname(family + " Bold") or fontfile,
            get_nt_fname(family + " Italic") or
                get_nt_fname(family + " Oblique") or fontfile,
            get_nt_fname(family + " Bold Italic") or
                get_nt_fname(family + " Bold Oblique") or fontfile,
        ]
        return variants
Example #48
0
 def parseHTML(data, none):
     log.error(
         "You need xhtml2pdf installed to use the raw HTML directive.")
     return []
    def write(self, *ignored):

        self.init_document_data()

        if self.config.pdf_verbosity > 1:
            log.setLevel(logging.DEBUG)
        elif self.config.pdf_verbosity > 0:
            log.setLevel(logging.INFO)

        for entry in self.document_data:
            try:
                docname, targetname, title, author = entry[:4]
                # Custom options per document
                if len(entry) > 4 and isinstance(entry[4], dict):
                    opts = entry[4]
                else:
                    opts = {}
                self.info("processing " + targetname + "... ", nonl=1)
                self.opts = opts

                class dummy:
                    extensions = self.config.pdf_extensions

                createpdf.add_extensions(dummy())

                self.page_template = opts.get('pdf_page_template',
                                              self.config.pdf_page_template)

                docwriter = PDFWriter(
                    self,
                    stylesheets=opts.get('pdf_stylesheets',
                                         self.config.pdf_stylesheets),
                    language=opts.get('pdf_language',
                                      self.config.pdf_language),
                    breaklevel=opts.get('pdf_break_level',
                                        self.config.pdf_break_level),
                    breakside=opts.get('pdf_breakside',
                                       self.config.pdf_breakside),
                    fontpath=opts.get('pdf_font_path',
                                      self.config.pdf_font_path),
                    fitmode=opts.get('pdf_fit_mode', self.config.pdf_fit_mode),
                    compressed=opts.get('pdf_compressed',
                                        self.config.pdf_compressed),
                    inline_footnotes=opts.get(
                        'pdf_inline_footnotes',
                        self.config.pdf_inline_footnotes),
                    splittables=opts.get('pdf_splittables',
                                         self.config.pdf_splittables),
                    default_dpi=opts.get('pdf_default_dpi',
                                         self.config.pdf_default_dpi),
                    page_template=self.page_template,
                    invariant=opts.get('pdf_invariant',
                                       self.config.pdf_invariant),
                    real_footnotes=opts.get('pdf_real_footnotes',
                                            self.config.pdf_real_footnotes),
                    use_toc=opts.get('pdf_use_toc', self.config.pdf_use_toc),
                    toc_depth=opts.get('pdf_toc_depth',
                                       self.config.pdf_toc_depth),
                    use_coverpage=opts.get('pdf_use_coverpage',
                                           self.config.pdf_use_coverpage),
                    use_numbered_links=opts.get(
                        'pdf_use_numbered_links',
                        self.config.pdf_use_numbered_links),
                    fit_background_mode=opts.get(
                        'pdf_fit_background_mode',
                        self.config.pdf_fit_background_mode),
                    baseurl=opts.get('pdf_baseurl', self.config.pdf_baseurl),
                    section_header_depth=opts.get(
                        'section_header_depth',
                        self.config.section_header_depth),
                    srcdir=self.srcdir,
                    style_path=opts.get('pdf_style_path',
                                        self.config.pdf_style_path),
                    floating_images=opts.get('pdf_floating_images',
                                             self.config.pdf_floating_images),
                    config=self.config,
                )

                tgt_file = path.join(self.outdir, targetname + self.out_suffix)
                destination = FileOutput(destination=open(tgt_file, 'wb'),
                                         encoding='utf-8')
                doctree = self.assemble_doctree(
                    docname,
                    title,
                    author,
                    appendices=opts.get('pdf_appendices',
                                        self.config.pdf_appendices) or [])
                doctree.settings.author = author
                doctree.settings.title = title
                self.info("done")
                self.info("writing " + targetname + "... ", nonl=1)
                docwriter.write(doctree, destination)
                self.info("done")
            except Exception, e:
                log.error(str(e))
                print_exc()
                self.info(red("FAILED"))
Example #50
0
    def __init__(self, flist, font_path=None, style_path=None, def_dpi=300):
        log.info('Using stylesheets: %s' % ','.join(flist))
        # find base path
        if hasattr(sys, 'frozen'):
            self.PATH = abspath(dirname(sys.executable))
        else:
            self.PATH = abspath(dirname(__file__))

        # flist is a list of stylesheet filenames.
        # They will be loaded and merged in order.
        # but the two default stylesheets will always
        # be loaded first
        flist = [
            join(self.PATH, 'styles', 'styles.style'),
            join(self.PATH, 'styles', 'default.style')
        ] + flist

        self.def_dpi = def_dpi
        if font_path is None:
            font_path = []
        font_path += ['.', os.path.join(self.PATH, 'fonts')]
        self.FontSearchPath = [os.path.expanduser(p) for p in font_path]

        if style_path is None:
            style_path = []
        style_path += [
            '.', os.path.join(self.PATH, 'styles'), '~/.rst2pdf/styles'
        ]
        self.StyleSearchPath = [os.path.expanduser(p) for p in style_path]
        self.FontSearchPath = list(set(self.FontSearchPath))
        self.StyleSearchPath = list(set(self.StyleSearchPath))

        log.info('FontPath:%s' % self.FontSearchPath)
        log.info('StylePath:%s' % self.StyleSearchPath)

        findfonts.flist = self.FontSearchPath
        # Page width, height
        self.pw = 0
        self.ph = 0

        # Page size [w,h]
        self.ps = None

        # Margins (top,bottom,left,right,gutter)
        self.tm = 0
        self.bm = 0
        self.lm = 0
        self.rm = 0
        self.gm = 0

        # text width
        self.tw = 0

        # Default emsize, later it will be the fontSize of the base style
        self.emsize = 10

        self.languages = []

        ssdata = self.readSheets(flist)

        # Get pageSetup data from all stylessheets in order:
        self.ps = pagesizes.A4
        self.page = {}
        for data, ssname in ssdata:
            page = data.get('pageSetup', {})
            if page:
                self.page.update(page)
                pgs = page.get('size', None)
                if pgs:  # A standard size
                    pgs = pgs.upper()
                    if pgs in pagesizes.__dict__:
                        self.ps = list(pagesizes.__dict__[pgs])
                        self.psname = pgs
                        if 'width' in self.page:
                            del (self.page['width'])
                        if 'height' in self.page:
                            del (self.page['height'])
                    elif pgs.endswith('-LANDSCAPE'):
                        self.psname = pgs.split('-')[0]
                        self.ps = list(
                            pagesizes.landscape(
                                pagesizes.__dict__[self.psname]))
                        if 'width' in self.page:
                            del (self.page['width'])
                        if 'height' in self.page:
                            del (self.page['height'])
                    else:
                        log.critical('Unknown page size %s in stylesheet %s' %
                                     (page['size'], ssname))
                        continue
                else:  # A custom size
                    if 'size' in self.page:
                        del (self.page['size'])
                    # The sizes are expressed in some unit.
                    # For example, 2cm is 2 centimeters, and we need
                    # to do 2*cm (cm comes from reportlab.lib.units)
                    if 'width' in page:
                        self.ps[0] = self.adjustUnits(page['width'])
                    if 'height' in page:
                        self.ps[1] = self.adjustUnits(page['height'])
                self.pw, self.ph = self.ps
                if 'margin-left' in page:
                    self.lm = self.adjustUnits(page['margin-left'])
                if 'margin-right' in page:
                    self.rm = self.adjustUnits(page['margin-right'])
                if 'margin-top' in page:
                    self.tm = self.adjustUnits(page['margin-top'])
                if 'margin-bottom' in page:
                    self.bm = self.adjustUnits(page['margin-bottom'])
                if 'margin-gutter' in page:
                    self.gm = self.adjustUnits(page['margin-gutter'])
                if 'spacing-header' in page:
                    self.ts = self.adjustUnits(page['spacing-header'])
                if 'spacing-footer' in page:
                    self.bs = self.adjustUnits(page['spacing-footer'])
                if 'firstTemplate' in page:
                    self.firstTemplate = page['firstTemplate']

                # tw is the text width.
                # We need it to calculate header-footer height
                # and compress literal blocks.
                self.tw = self.pw - self.lm - self.rm - self.gm

        # Get page templates from all stylesheets
        self.pageTemplates = {}
        for data, ssname in ssdata:
            templates = data.get('pageTemplates', {})
            # templates is a dictionary of pageTemplates
            for key in templates:
                template = templates[key]
                # template is a dict.
                # template[´frames'] is a list of frames
                if key in self.pageTemplates:
                    self.pageTemplates[key].update(template)
                else:
                    self.pageTemplates[key] = template

        # Get font aliases from all stylesheets in order
        self.fontsAlias = {}
        for data, ssname in ssdata:
            self.fontsAlias.update(data.get('fontsAlias', {}))

        embedded_fontnames = []
        self.embedded = []
        # Embed all fonts indicated in all stylesheets
        for data, ssname in ssdata:
            embedded = data.get('embeddedFonts', [])

            for font in embedded:
                try:
                    # Just a font name, try to embed it
                    if isinstance(font, str):
                        # See if we can find the font
                        fname, pos = findfonts.guessFont(font)
                        if font in embedded_fontnames:
                            pass
                        else:
                            fontList = findfonts.autoEmbed(font)
                            if fontList:
                                embedded_fontnames.append(font)
                        if not fontList:
                            if (fname, pos) in embedded_fontnames:
                                fontList = None
                            else:
                                fontList = findfonts.autoEmbed(fname)
                        if fontList is not None:
                            self.embedded += fontList
                            # Maybe the font we got is not called
                            # the same as the one we gave
                            # so check that out
                            suff = ["", "-Oblique", "-Bold", "-BoldOblique"]
                            if not fontList[0].startswith(font):
                                # We need to create font aliases, and use them
                                for fname, aliasname in zip(
                                        fontList,
                                    [font + suffix for suffix in suff]):
                                    self.fontsAlias[aliasname] = fname
                        continue

                    # Each "font" is a list of four files, which will be
                    # used for regular / bold / italic / bold+italic
                    # versions of the font.
                    # If your font doesn't have one of them, just repeat
                    # the regular font.

                    # Example, using the Tuffy font from
                    # http://tulrich.com/fonts/
                    # "embeddedFonts" : [
                    #                    ["Tuffy.ttf",
                    #                     "Tuffy_Bold.ttf",
                    #                     "Tuffy_Italic.ttf",
                    #                     "Tuffy_Bold_Italic.ttf"]
                    #                   ],

                    # The fonts will be registered with the file name,
                    # minus the extension.

                    if font[0].lower().endswith('.ttf'):  # A True Type font
                        for variant in font:
                            location = self.findFont(variant)
                            pdfmetrics.registerFont(
                                TTFont(str(variant.split('.')[0]), location))
                            log.info('Registering font: %s from %s' %
                                     (str(variant.split('.')[0]), location))
                            self.embedded.append(str(variant.split('.')[0]))

                        # And map them all together
                        regular, bold, italic, bolditalic = [
                            variant.split('.')[0] for variant in font
                        ]
                        addMapping(regular, 0, 0, regular)
                        addMapping(regular, 0, 1, italic)
                        addMapping(regular, 1, 0, bold)
                        addMapping(regular, 1, 1, bolditalic)
                    else:  # A Type 1 font
                        # For type 1 fonts we require
                        # [FontName,regular,italic,bold,bolditalic]
                        # where each variant is a (pfbfile,afmfile) pair.
                        # For example, for the URW palladio from TeX:
                        # ["Palatino",("uplr8a.pfb","uplr8a.afm"),
                        #             ("uplri8a.pfb","uplri8a.afm"),
                        #             ("uplb8a.pfb","uplb8a.afm"),
                        #             ("uplbi8a.pfb","uplbi8a.afm")]
                        regular = pdfmetrics.EmbeddedType1Face(*font[1])
                        italic = pdfmetrics.EmbeddedType1Face(*font[2])
                        bold = pdfmetrics.EmbeddedType1Face(*font[3])
                        bolditalic = pdfmetrics.EmbeddedType1Face(*font[4])

                except Exception as e:
                    try:
                        if isinstance(font, list):
                            fname = font[0]
                        else:
                            fname = font
                        log.error("Error processing font %s: %s",
                                  os.path.splitext(fname)[0], str(e))
                        log.error("Registering %s as Helvetica alias", fname)
                        self.fontsAlias[fname] = 'Helvetica'
                    except Exception as e:
                        log.critical("Error processing font %s: %s", fname,
                                     str(e))
                        continue

        # Go though all styles in all stylesheets and find all fontNames.
        # Then decide what to do with them
        for data, ssname in ssdata:
            for [skey, style] in self.stylepairs(data):
                for key in style:
                    if key == 'fontName' or key.endswith('FontName'):
                        # It's an alias, replace it
                        if style[key] in self.fontsAlias:
                            style[key] = self.fontsAlias[style[key]]
                        # Embedded already, nothing to do
                        if style[key] in self.embedded:
                            continue
                        # Standard font, nothing to do
                        if style[key] in ("Courier", "Courier-Bold",
                                          "Courier-BoldOblique",
                                          "Courier-Oblique", "Helvetica",
                                          "Helvetica-Bold",
                                          "Helvetica-BoldOblique",
                                          "Helvetica-Oblique", "Symbol",
                                          "Times-Bold", "Times-BoldItalic",
                                          "Times-Italic", "Times-Roman",
                                          "ZapfDingbats"):
                            continue
                        # Now we need to do something
                        # See if we can find the font
                        fname, pos = findfonts.guessFont(style[key])

                        if style[key] in embedded_fontnames:
                            pass
                        else:
                            fontList = findfonts.autoEmbed(style[key])
                            if fontList:
                                embedded_fontnames.append(style[key])
                        if not fontList:
                            if (fname, pos) in embedded_fontnames:
                                fontList = None
                            else:
                                fontList = findfonts.autoEmbed(fname)
                            if fontList:
                                embedded_fontnames.append((fname, pos))
                        if fontList:
                            self.embedded += fontList
                            # Maybe the font we got is not called
                            # the same as the one we gave so check that out
                            suff = ["", "-Bold", "-Oblique", "-BoldOblique"]
                            if not fontList[0].startswith(style[key]):
                                # We need to create font aliases, and use them
                                basefname = style[key].split('-')[0]
                                for fname, aliasname in zip(
                                        fontList,
                                    [basefname + suffix for suffix in suff]):
                                    self.fontsAlias[aliasname] = fname
                                style[key] = self.fontsAlias[basefname +
                                                             suff[pos]]
                        else:
                            log.error(
                                'Unknown font: "%s",'
                                "replacing with Helvetica", style[key])
                            style[key] = "Helvetica"

        # log.info('FontList: %s'%self.embedded)
        # log.info('FontAlias: %s'%self.fontsAlias)
        # Get styles from all stylesheets in order
        self.stylesheet = {}
        self.styles = []
        self.linkColor = 'navy'
        # FIXME: linkColor should probably not be a global
        #        style, and tocColor should probably not
        #        be a special case, but for now I'm going
        #        with the flow...
        self.tocColor = None
        for data, ssname in ssdata:
            self.linkColor = data.get('linkColor') or self.linkColor
            self.tocColor = data.get('tocColor') or self.tocColor
            for [skey, style] in self.stylepairs(data):
                sdict = {}
                # FIXME: this is done completely backwards
                for key in style:
                    # Handle color references by name
                    if key == 'color' or key.endswith('Color') and style[key]:
                        style[key] = formatColor(style[key])

                    # Yet another workaround for the unicode bug in
                    # reportlab's toColor
                    elif key == 'commands':
                        style[key] = validateCommands(style[key])
                        # for command in style[key]:
                        # c=command[0].upper()
                        # if c=='ROWBACKGROUNDS':
                        # command[3]=[str(c) for c in command[3]]
                        # elif c in ['BOX','INNERGRID'] or c.startswith('LINE'):
                        # command[4]=str(command[4])

                    # Handle alignment constants
                    elif key == 'alignment':
                        style[key] = dict(
                            TA_LEFT=0,
                            LEFT=0,
                            TA_CENTER=1,
                            CENTER=1,
                            TA_CENTRE=1,
                            CENTRE=1,
                            TA_RIGHT=2,
                            RIGHT=2,
                            TA_JUSTIFY=4,
                            JUSTIFY=4,
                            DECIMAL=8,
                        )[style[key].upper()]

                    elif key == 'language':
                        if not style[key] in self.languages:
                            self.languages.append(style[key])

                    # Make keys str instead of unicode (required by reportlab)
                    sdict[str(key)] = style[key]
                    sdict['name'] = skey
                # If the style already exists, update it
                if skey in self.stylesheet:
                    self.stylesheet[skey].update(sdict)
                else:  # New style
                    self.stylesheet[skey] = sdict
                    self.styles.append(sdict)

        # If the stylesheet has a style name docutils won't reach
        # make a copy with a sanitized name.
        # This may make name collisions possible but that should be
        # rare (who would have custom_name and custom-name in the
        # same stylesheet? ;-)
        # Issue 339

        styles2 = []
        for s in self.styles:
            if not re.match("^[a-z](-?[a-z0-9]+)*$", s['name']):
                s2 = copy.copy(s)
                s2['name'] = docutils.nodes.make_id(s['name'])
                log.warning(('%s is an invalid docutils class name, adding ' +
                             'alias %s') % (s['name'], s2['name']))
                styles2.append(s2)
        self.styles.extend(styles2)

        # And create  reportlabs stylesheet
        self.StyleSheet = StyleSheet1()
        # Patch to make the code compatible with reportlab from SVN 2.4+ and
        # 2.4
        if not hasattr(self.StyleSheet, 'has_key'):
            self.StyleSheet.__class__.has_key = lambda s, k: k in s
        for s in self.styles:
            if 'parent' in s:
                if s['parent'] is None:
                    if s['name'] != 'base':
                        s['parent'] = self.StyleSheet['base']
                    else:
                        del (s['parent'])
                else:
                    s['parent'] = self.StyleSheet[s['parent']]
            else:
                if s['name'] != 'base':
                    s['parent'] = self.StyleSheet['base']

            # If the style has no bulletFontName but it has a fontName, set it
            if ('bulletFontName' not in s) and ('fontName' in s):
                s['bulletFontName'] = s['fontName']

            hasFS = True
            # Adjust fontsize units
            if 'fontSize' not in s:
                s['fontSize'] = s['parent'].fontSize
                s['trueFontSize'] = None
                hasFS = False
            elif 'parent' in s:
                # This means you can set the fontSize to
                # "2cm" or to "150%" which will be calculated
                # relative to the parent style
                s['fontSize'] = self.adjustUnits(s['fontSize'],
                                                 s['parent'].fontSize)
                s['trueFontSize'] = s['fontSize']
            else:
                # If s has no parent, it's base, which has
                # an explicit point size by default and %
                # makes no sense, but guess it as % of 10pt
                s['fontSize'] = self.adjustUnits(s['fontSize'], 10)

            # If the leading is not set, but the size is, set it
            if 'leading' not in s and hasFS:
                s['leading'] = 1.2 * s['fontSize']

            # If the bullet font size is not set, set it as fontSize
            if ('bulletFontSize' not in s) and ('fontSize' in s):
                s['bulletFontSize'] = s['fontSize']

            # If the borderPadding is a list and wordaxe <=0.3.2,
            # convert it to an integer. Workaround for Issue
            if ('borderPadding' in s and HAS_WORDAXE
                    and wordaxe_version <= 'wordaxe 0.3.2'
                    and isinstance(s['borderPadding'], list)):
                log.warning(('Using a borderPadding list in style %s with ' +
                             'wordaxe <= 0.3.2. That is  not supported, so ' +
                             'it will probably look wrong') % s['name'])
                s['borderPadding'] = s['borderPadding'][0]

            self.StyleSheet.add(ParagraphStyle(**s))

        self.emsize = self['base'].fontSize
        # Make stdFont the basefont, for Issue 65
        reportlab.rl_config.canvas_basefontname = self['base'].fontName
        # Make stdFont the default font for table cell styles (Issue 65)
        reportlab.platypus.tables.CellStyle.fontname = self['base'].fontName
Example #51
0
    def translate(self):
        visitor = PDFTranslator(self.document, self.builder)
        self.document.walkabout(visitor)
        lang = self.config.language or 'en'
        langmod = get_language_available(lang)[2]
        self.docutils_languages = {lang: langmod}

        # Generate Contents topic manually
        if self.use_toc:
            contents=nodes.topic(classes=['contents'])
            contents+=nodes.title('')
            contents[0]+=nodes.Text(langmod.labels['contents'])
            contents['ids']=['Contents']
            pending=nodes.topic()
            contents.append(pending)
            pending.details={}
            self.document.insert(0,nodes.raw(text='SetPageCounter 1 arabic', format='pdf'))
            self.document.insert(0,nodes.raw(text='OddPageBreak %s'%self.page_template, format='pdf'))
            self.document.insert(0,contents)
            self.document.insert(0,nodes.raw(text='SetPageCounter 1 lowerroman', format='pdf'))
            contTrans=PDFContents(self.document)
            contTrans.toc_depth = self.toc_depth
            contTrans.startnode=pending
            contTrans.apply()

        if self.use_coverpage:
            # Generate cover page

            # FIXME: duplicate from createpdf, refactor!
            # Add the Sphinx template paths
            def add_template_path(path):
                return os.path.join(self.srcdir, path)

            jinja_env = jinja2.Environment(
                loader=jinja2.FileSystemLoader([
                        self.srcdir, os.path.expanduser('~/.rst2pdf'),
                        os.path.join(self.PATH,'templates')] +
                        list(map(add_template_path, self.config.templates_path))),
                autoescape=jinja2.select_autoescape(['html', 'xml'])
            )

            try:
                template = jinja_env.get_template(self.config.pdf_cover_template)
            except jinja2.TemplateNotFound:
                log.error("Can't find cover template %s, using default"%self.config.pdf_cover_template)
                template = jinja_env.get_template('sphinxcover.tmpl')

            # This is what's used in the python docs because
            # Latex does a manual linebreak. This sucks.
            authors=self.document.settings.author.split('\\')

            # Honour the "today" config setting
            if self.config.today :
                date = self.config.today
            else:
                date=time.strftime(self.config.today_fmt or _('%B %d, %Y'))

            # Feed data to the template, get restructured text.
            cover_text = template.render(
                                title=self.document.settings.title or visitor.elements['title'],
                                subtitle='%s %s'%(_('version'),self.config.version),
                                authors=authors,
                                date=date
                                )

            cover_tree = docutils.core.publish_doctree(cover_text)
            self.document.insert(0, cover_tree)

        sio=BytesIO()

        if self.invariant:
            createpdf.patch_PDFDate()
            createpdf.patch_digester()

        createpdf.RstToPdf(sphinx=True,
                 stylesheets=self.stylesheets,
                 language=self.__language,
                 breaklevel=self.breaklevel,
                 breakside=self.breakside,
                 fit_mode=self.fitmode,
                 font_path=self.fontpath,
                 inline_footnotes=self.inline_footnotes,
                 highlightlang=self.highlightlang,
                 splittables=self.splittables,
                 style_path=self.style_path,
                 repeat_table_rows=self.repeat_table_rows,
                 basedir=self.srcdir,
                 def_dpi=self.default_dpi,
                 real_footnotes=self.real_footnotes,
                 numbered_links=self.use_numbered_links,
                 background_fit_mode=self.fit_background_mode,
                 baseurl=self.baseurl,
                 section_header_depth=self.section_header_depth
                ).createPdf(doctree=self.document,
                    output=sio,
                    compressed=self.compressed)
        self.output=sio.getvalue()
Example #52
0
    def get_backend(self, uri, client):
        """
        Given the filename of an image, return (fname, backend).

        fname is the filename to be used (could be the same as filename,
        or something different if the image had to be converted or is
        missing), and backend is an Image class that can handle fname.

        If uri ends with '.*' then the returned filename will be the best
        quality supported at the moment.

        That means:  PDF > SVG > anything else
        """
        backend = defaultimage

        # Extract all the information from the URI
        filename, extension, options = self.split_uri(uri)

        if '*' in filename:
            preferred = ['gif', 'jpg', 'png', 'svg', 'pdf']

            # Find out what images are available
            available = glob.glob(filename)
            cfn = available[0]
            cv = -10
            for fn in available:
                ext = fn.split('.')[-1]
                if ext in preferred:
                    v = preferred.index(ext)
                else:
                    v = -1
                if v > cv:
                    cv = v
                    cfn = fn
            # cfn should have our favourite type of
            # those available
            filename = cfn
            extension = cfn.split('.')[-1]
            uri = filename

        # If the image doesn't exist, we use a 'missing' image
        if not os.path.exists(filename):
            log.error("Missing image file: %s", filename)
            filename = missing

        if extension in ['svg', 'svgz']:
            log.info('Backend for %s is SVGIMage' % filename)
            backend = SVGImage

        elif extension in ['pdf']:
            if VectorPdf is not None and filename is not missing:
                backend = VectorPdf
                filename = uri

            # PDF images are implemented by converting via PythonMagick
            # w,h are in pixels. I need to set the density
            # of the image to  the right dpi so this
            # looks decent
            elif LazyImports.PMImage or LazyImports.gfx:
                filename = self.raster(filename, client)
            else:
                log.warning('Minimal PDF image support requires ' +
                            'PythonMagick or the vectorpdf extension [%s]',
                            filename)
                filename = missing
        elif extension != 'jpg' and not LazyImports.PILImage:
            if LazyImports.PMImage:
                # Need to convert to JPG via PythonMagick
                filename = self.raster(filename, client)
            else:
                # No way to make this work
                log.error('To use a %s image you need PIL installed [%s]',
                          extension, filename)
                filename = missing
        return filename, backend
Example #53
0
def autoEmbed(fname):
    """Given a font name, does a best-effort of embedding
    said font and its variants.

    Returns a list of the font names it registered with ReportLab.

    """
    log.info("Trying to embed %s" % fname)
    fontList = []
    variants = []
    f = findFont(fname)
    if f:  # We have this font located
        if f[0].lower().endswith(".afm"):  # Type 1 font
            family = families[f[2]]

            # Register the whole family of faces
            faces = [
                pdfmetrics.EmbeddedType1Face(*fonts[fn.lower()][:2]) for fn in family
            ]
            for face in faces:
                pdfmetrics.registerTypeFace(face)

            for face, name in zip(faces, family):
                fontList.append(name)
                font = pdfmetrics.Font(face, name, "WinAnsiEncoding")
                log.info("Registering font: %s from %s" % (name, face.getFontFiles()))
                pdfmetrics.registerFont(font)

            # Map the variants
            regular, italic, bold, bolditalic = family
            for n in fname, regular:
                addMapping(n, 0, 0, regular)
                addMapping(n, 0, 1, italic)
                addMapping(n, 1, 0, bold)
                addMapping(n, 1, 1, bolditalic)
            log.info("Embedding as %s" % fontList)
            return fontList
        else:  # A TTF font
            variants = [fonts[x.lower()][0] for x in families[f[2]]]
    if not variants:  # Try fc-match
        variants = findTTFont(fname)
    # It is a TT Font and we found it using fc-match (or found *something*)
    if variants:
        for variant in variants:
            vname = os.path.basename(variant)[:-4]
            try:
                if vname not in pdfmetrics._fonts:
                    _font = TTFont(vname, variant)
                    log.info("Registering font: %s from %s" % (vname, variant))
                    pdfmetrics.registerFont(_font)
            except TTFError:
                log.error("Error registering font: %s from %s" % (vname, variant))
            else:
                fontList.append(vname)
        regular, bold, italic, bolditalic = [
            os.path.basename(variant)[:-4] for variant in variants
        ]
        addMapping(regular, 0, 0, regular)
        addMapping(regular, 0, 1, italic)
        addMapping(regular, 1, 0, bold)
        addMapping(regular, 1, 1, bolditalic)
        log.info("Embedding via findTTFont as %s" % fontList)
    return fontList
Example #54
0
    def translate(self):
        visitor = PDFTranslator(self.document, self.builder)
        self.document.walkabout(visitor)
        lang = self.config.language or 'en'
        langmod = get_language_available(lang)[2]
        self.docutils_languages = {lang: langmod}

        # Generate Contents topic manually
        if self.use_toc:
            contents=nodes.topic(classes=['contents'])
            contents+=nodes.title('')
            contents[0]+=nodes.Text(langmod.labels['contents'])
            contents['ids']=['Contents']
            pending=nodes.topic()
            contents.append(pending)
            pending.details={}
            self.document.insert(0,nodes.raw(text='SetPageCounter 1 arabic', format='pdf'))
            self.document.insert(0,nodes.raw(text='OddPageBreak %s'%self.page_template, format='pdf'))
            self.document.insert(0,contents)
            self.document.insert(0,nodes.raw(text='SetPageCounter 1 lowerroman', format='pdf'))
            contTrans=PDFContents(self.document)
            contTrans.toc_depth = self.toc_depth
            contTrans.startnode=pending
            contTrans.apply()

        if self.use_coverpage:
            # Generate cover page

            # FIXME: duplicate from createpdf, refactor!

            # Find cover template, save it in cover_file
            def find_cover(name):
                cover_path=[self.srcdir, os.path.expanduser('~/.rst2pdf'),
                                            os.path.join(self.PATH,'templates')]

                # Add the Sphinx template paths
                def add_template_path(path):
                    return os.path.join(self.srcdir, path)

                cover_path.extend(map(add_template_path, self.config.templates_path))

                cover_file=None
                for d in cover_path:
                    if os.path.exists(os.path.join(d,name)):
                        cover_file=os.path.join(d,name)
                        break
                return cover_file

            cover_file=find_cover(self.config.pdf_cover_template)
            if cover_file is None:
                log.error("Can't find cover template %s, using default"%self.custom_cover)
                cover_file=find_cover('sphinxcover.tmpl')

            # This is what's used in the python docs because
            # Latex does a manual linebreak. This sucks.
            authors=self.document.settings.author.split('\\')

            # Feed data to the template, get restructured text.
            cover_text = createpdf.renderTemplate(tname=cover_file,
                                title=self.document.settings.title or visitor.elements['title'],
                                subtitle='%s %s'%(_('version'),self.config.version),
                                authors=authors,
                                date=ustrftime(self.config.today_fmt or _('%B %d, %Y'))
                                )

            cover_tree = docutils.core.publish_doctree(cover_text)
            self.document.insert(0, cover_tree)

        sio=StringIO()

        if self.invariant:
            createpdf.patch_PDFDate()
            createpdf.patch_digester()

        createpdf.RstToPdf(sphinx=True,
                 stylesheets=self.stylesheets,
                 language=self.__language,
                 breaklevel=self.breaklevel,
                 breakside=self.breakside,
                 fit_mode=self.fitmode,
                 font_path=self.fontpath,
                 inline_footnotes=self.inline_footnotes,
                 highlightlang=self.highlightlang,
                 splittables=self.splittables,
                 style_path=self.style_path,
                 basedir=self.srcdir,
                 def_dpi=self.default_dpi,
                 real_footnotes=self.real_footnotes,
                 numbered_links=self.use_numbered_links,
                 background_fit_mode=self.fit_background_mode,
                 baseurl=self.baseurl,
                 section_header_depth=self.section_header_depth
                ).createPdf(doctree=self.document,
                    output=sio,
                    compressed=self.compressed)
        self.output=sio.getvalue()