当前位置: 首页>>代码示例>>Python>>正文


Python pandocfilters.Image方法代码示例

本文整理汇总了Python中pandocfilters.Image方法的典型用法代码示例。如果您正苦于以下问题:Python pandocfilters.Image方法的具体用法?Python pandocfilters.Image怎么用?Python pandocfilters.Image使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在pandocfilters的用法示例。


在下文中一共展示了pandocfilters.Image方法的12个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: _extract_attrs

# 需要导入模块: import pandocfilters [as 别名]
# 或者: from pandocfilters import Image [as 别名]
def _extract_attrs(x, n):
    """Extracts attributes for an image in the element list `x`.  The
    attributes begin at index `n`.  Extracted elements are deleted
    from the list.
    """
    try:  #  Try the standard call from pandocxnos first
        return extract_attrs(x, n)

    except (ValueError, IndexError):

        if PANDOCVERSION < '1.16':
            # Look for attributes attached to the image path, as occurs with
            # image references for pandoc < 1.16 (pandoc-fignos Issue #14).
            # See http://pandoc.org/MANUAL.html#images for the syntax.
            # Note: This code does not handle the "optional title" for
            # image references (search for link_attributes in pandoc's docs).
            assert x[n-1]['t'] == 'Image'
            image = x[n-1]
            s = image['c'][-1][0]
            if '%20%7B' in s:
                path = s[:s.index('%20%7B')]
                attrstr = unquote(s[s.index('%7B'):])
                image['c'][-1][0] = path  # Remove attr string from the path
                return PandocAttributes(attrstr.strip(), 'markdown')
        raise 
开发者ID:tomduck,项目名称:pandoc-fignos,代码行数:27,代码来源:pandoc_fignos.py

示例2: tikz

# 需要导入模块: import pandocfilters [as 别名]
# 或者: from pandocfilters import Image [as 别名]
def tikz(key, value, format, meta):
    if key == 'RawBlock':
        [fmt, code] = value
        if fmt == "latex" and re.match("\\\\begin{tikzpicture}", code):
            outfile = imagedir + '/' + sha1(code)
            if format == "html":
                filetype = "png"
            elif format == "latex":
                filetype = "pdf"
            else:
                filetype = "png"
            src = outfile + '.' + filetype
            if not os.path.isfile(src):
                try:
                    os.mkdir(imagedir)
                    sys.stderr.write('Created directory ' + imagedir + '\n')
                except OSError:
                    pass
                tikz2image(code, filetype, outfile)
                sys.stderr.write('Created image ' + src + '\n')
            return Para([Image(['', [], []], [], [src, ""])]) 
开发者ID:sergiocorreia,项目名称:panflute,代码行数:23,代码来源:tikz.py

示例3: abc

# 需要导入模块: import pandocfilters [as 别名]
# 或者: from pandocfilters import Image [as 别名]
def abc(key, value, format, meta):
    if key == 'CodeBlock':
        [[ident, classes, keyvals], code] = value
        if "abc" in classes:
            outfile = imagedir + '/' + sha1(code)
            if format == "html":
                filetype = "png"
            elif format == "latex":
                filetype = "pdf"
            else:
                filetype = "png"
            src = outfile + '.' + filetype
            if not os.path.isfile(src):
                try:
                    os.mkdir(imagedir)
                    sys.stderr.write('Created directory ' + imagedir + '\n')
                except OSError:
                    pass
                abc2eps(code.encode("utf-8"), filetype, outfile)
                sys.stderr.write('Created image ' + src + '\n')
            return Para([Image(['', [], []], [], [src, ""])]) 
开发者ID:sergiocorreia,项目名称:panflute,代码行数:23,代码来源:abc.py

示例4: process_figures

# 需要导入模块: import pandocfilters [as 别名]
# 或者: from pandocfilters import Image [as 别名]
def process_figures(key, value, fmt, meta):  # pylint: disable=unused-argument
    """Processes the figures."""

    # Process figures wrapped in Para elements
    if key == 'Para' and len(value) == 1 and \
      value[0]['t'] == 'Image' and value[0]['c'][-1][1].startswith('fig:'):

        # Process the figure and add markup
        fig = _process_figure(key, value, fmt)
        if 'attrs' in fig:
            _adjust_caption(fmt, fig, value)
        return _add_markup(fmt, fig, value)

    if key == 'Div' and LABEL_PATTERN.match(value[0][0]):
        fig = _process_figure(key, value, fmt)
    
    return None


# TeX blocks -----------------------------------------------------------------

# Define an environment that disables figure caption prefixes.  Counters
# must be saved and later restored.  The \thefigure and \theHfigure counter
# must be set to something unique so that duplicate internal names are avoided
# (see Sect. 3.2 of
# http://ctan.mirror.rafal.ca/macros/latex/contrib/hyperref/doc/manual.html). 
开发者ID:tomduck,项目名称:pandoc-fignos,代码行数:28,代码来源:pandoc_fignos.py

示例5: plantuml

# 需要导入模块: import pandocfilters [as 别名]
# 或者: from pandocfilters import Image [as 别名]
def plantuml(key, value, format_, _):
    if key == 'CodeBlock':
        [[ident, classes, keyvals], code] = value

        if "plantuml" in classes:
            caption, typef, keyvals = get_caption(keyvals)

            filename = get_filename4code("plantuml", code)
            filetype = get_extension(format_, "png", html="svg", latex="png")

            src = filename + '.uml'
            dest = filename + '.' + filetype

            # Generate image only once
            if not os.path.isfile(dest):
                txt = code.encode(sys.getfilesystemencoding())
                if not txt.startswith(b"@start"):
                    txt = b"@startuml\n" + txt + b"\n@enduml\n"
                with open(src, "wb") as f:
                    f.write(txt)

                subprocess.check_call(PLANTUML_BIN.split() +
                                      ["-t" + filetype, src])
                sys.stderr.write('Created image ' + dest + '\n')

            # Update symlink each run
            for ind, keyval in enumerate(keyvals):
                if keyval[0] == 'plantuml-filename':
                    link = keyval[1]
                    keyvals.pop(ind)
                    rel_mkdir_symlink(dest, link)
                    dest = link
                    break

            return Para([Image([ident, [], keyvals], caption, [dest, typef])]) 
开发者ID:timofurrer,项目名称:pandoc-plantuml-filter,代码行数:37,代码来源:pandoc_plantuml_filter.py

示例6: graphviz

# 需要导入模块: import pandocfilters [as 别名]
# 或者: from pandocfilters import Image [as 别名]
def graphviz(key, value, format, meta):
    if key == 'CodeBlock':
        [[ident, classes, keyvals], code] = value
        caption = "caption"
        if "graphviz" in classes:
            G = pygraphviz.AGraph(string=code)
            G.layout()
            filename = sha1(code)
            if format == "html":
                filetype = "png"
            elif format == "latex":
                filetype = "pdf"
            else:
                filetype = "png"
            alt = Str(caption)
            src = imagedir + '/' + filename + '.' + filetype
            if not os.path.isfile(src):
                try:
                    os.mkdir(imagedir)
                    sys.stderr.write('Created directory ' + imagedir + '\n')
                except OSError:
                    pass
                G.draw(src)
                sys.stderr.write('Created image ' + src + '\n')
            tit = ""
            return Para([Image(['', [], []], [alt], [src, tit])]) 
开发者ID:sergiocorreia,项目名称:panflute,代码行数:28,代码来源:graphviz.py

示例7: lily

# 需要导入模块: import pandocfilters [as 别名]
# 或者: from pandocfilters import Image [as 别名]
def lily(key, value, fmt, meta):
    if key == 'Code':
        [[ident, classes, kvs], contents] = value  # pylint:disable=I0011,W0612
        kvs = {key: value for key, value in kvs}
        if "ly" in classes:
            staffsize = kvs['staffsize'] if 'staffsize' in kvs else 20
            if fmt == "latex":
                if ident == "":
                    label = ""
                else:
                    label = '\\label{' + ident + '}'
                return latex(
                    '\\includely[staffsize=%s]{%s}' % (staffsize, contents) +
                    label
                )
            else:
                infile = contents + (
                    '.ly' if '.ly' not in contents else ''
                )
                with open(infile, 'r') as doc:
                    code = doc.read()
                return [
                    Image(['', [], []], [], [png(code, staffsize), ""])
                ]
    if key == 'CodeBlock':
        [[ident, classes, kvs], code] = value
        kvs = {key: value for key, value in kvs}
        if "ly" in classes:
            staffsize = kvs['staffsize'] if 'staffsize' in kvs else 20
            if fmt == "latex":
                if ident == "":
                    label = ""
                else:
                    label = '\\label{' + ident + '}'
                return latexblock(
                    '\\lily[staffsize=%s]{%s}' % (staffsize, code) +
                    label
                )
            else:
                return Para([Image(['', [], []], [], [png(code, staffsize), ""])]) 
开发者ID:sergiocorreia,项目名称:panflute,代码行数:42,代码来源:lilypond.py

示例8: url

# 需要导入模块: import pandocfilters [as 别名]
# 或者: from pandocfilters import Image [as 别名]
def url(self):
        'return an image link for existing/new output image-file'
        # pf.Image is an Inline element. Callers usually wrap it in a pf.Para
        return pf.Image([self.id_, self.classes, self.keyvals],
                        self.caption, [self.outfile, self.typef]) 
开发者ID:hertogp,项目名称:imagine,代码行数:7,代码来源:pandoc_imagine.py

示例9: image

# 需要导入模块: import pandocfilters [as 别名]
# 或者: from pandocfilters import Image [as 别名]
def image(self):
        'return an Image url or None to keep CodeBlock'
        # For cases where no handler could be associated with a fenced
        # codeblock, Handler itself will be the 'worker' who returns None
        # preserving the original codeblock as-is in the json AST.
        # Real workers (subclassing Handler) must override this method
        self.msg(2, 'CodeBlock ignored, keeping as-is')
        return None 
开发者ID:hertogp,项目名称:imagine,代码行数:10,代码来源:pandoc_imagine.py

示例10: _add_markup

# 需要导入模块: import pandocfilters [as 别名]
# 或者: from pandocfilters import Image [as 别名]
def _add_markup(fmt, fig, value):
    """Adds markup to the output."""

    # pylint: disable=global-statement
    global has_tagged_figures  # Flags a tagged figure was found

    if fig['is_unnumbered']:
        if fmt in ['latex', 'beamer']:
            # Use the no-prefix-figure-caption environment
            return [RawBlock('tex', r'\begin{fignos:no-prefix-figure-caption}'),
                    Para(value),
                    RawBlock('tex', r'\end{fignos:no-prefix-figure-caption}')]
        return None  # Nothing to do

    attrs = fig['attrs']
    ret = None

    if fmt in ['latex', 'beamer']:
        if fig['is_tagged']:  # A figure cannot be tagged if it is unnumbered
            # Use the tagged-figure environment
            has_tagged_figures = True
            ret = [RawBlock('tex', r'\begin{fignos:tagged-figure}[%s]' % \
                            str(targets[attrs.id].num)),
                   Para(value),
                   RawBlock('tex', r'\end{fignos:tagged-figure}')]
    elif fmt in ('html', 'html5', 'epub', 'epub2', 'epub3'):
        if LABEL_PATTERN.match(attrs.id):
            pre = RawBlock('html', '<div id="%s" class="fignos">'%attrs.id)
            post = RawBlock('html', '</div>')
            ret = [pre, Para(value), post]
            # Eliminate the id from the Image
            attrs.id = ''
            value[0]['c'][0] = attrs.list
    elif fmt == 'docx':
        # As per http://officeopenxml.com/WPhyperlink.php
        bookmarkstart = \
          RawBlock('openxml',
                   '<w:bookmarkStart w:id="0" w:name="%s"/>'
                   %attrs.id)
        bookmarkend = \
          RawBlock('openxml', '<w:bookmarkEnd w:id="0"/>')
        ret = [bookmarkstart, Para(value), bookmarkend]
    return ret 
开发者ID:tomduck,项目名称:pandoc-fignos,代码行数:45,代码来源:pandoc_fignos.py

示例11: gabc

# 需要导入模块: import pandocfilters [as 别名]
# 或者: from pandocfilters import Image [as 别名]
def gabc(key, value, fmt, meta):                   # pylint:disable=I0011,W0613
    """Handle gabc file inclusion and gabc code block."""
    if key == 'Code':
        [[ident, classes, kvs], contents] = value  # pylint:disable=I0011,W0612
        kvs = {key: value for key, value in kvs}
        if "gabc" in classes:
            if fmt == "latex":
                if ident == "":
                    label = ""
                else:
                    label = '\\label{' + ident + '}'
                return latex(
                    "\n\\smallskip\n{%\n" +
                    latexsnippet('\\gregorioscore{' + contents + '}', kvs) +
                    "%\n}" +
                    label
                )
            else:
                infile = contents + (
                    '.gabc' if '.gabc' not in contents else ''
                )
                with open(infile, 'r') as doc:
                    code = doc.read().split('%%\n')[1]
                return [Image(['', [], []], [], [
                    png(
                        contents,
                        latexsnippet('\\gregorioscore', kvs)
                    ),
                    ""
                ])]
    elif key == 'CodeBlock':
        [[ident, classes, kvs], contents] = value
        kvs = {key: value for key, value in kvs}
        if "gabc" in classes:
            if fmt == "latex":
                if ident == "":
                    label = ""
                else:
                    label = '\\label{' + ident + '}'
                return [latexblock(
                    "\n\\smallskip\n{%\n" +
                    latexsnippet('\\gabcsnippet{' + contents + '}', kvs) +
                    "%\n}" +
                    label
                    )]
            else:
                return Para([Image(['', [], []], [], [
                    png(
                        contents,
                        latexsnippet('\\gabcsnippet', kvs)
                    ),
                    ""
                ])]) 
开发者ID:sergiocorreia,项目名称:panflute,代码行数:55,代码来源:gabc.py

示例12: wrap_image_output

# 需要导入模块: import pandocfilters [as 别名]
# 或者: from pandocfilters import Image [as 别名]
def wrap_image_output(self, chunk_name, data, key, attrs):
        """
        Extra handling for images

        Parameters
        ----------
        chunk_name, data, key : str
        attrs: dict

        Returns
        -------
        Para[Image]
        """
        # TODO: interaction of output type and standalone.
        # TODO: this can be simplified, do the file-writing in one step
        def b64_encode(data):
            return base64.encodebytes(data.encode('utf-8')).decode('ascii')

        # TODO: dict of attrs on Stitcher.
        image_keys = {'width', 'height'}
        caption = attrs.get('fig.cap', '')

        def transform_key(k):
            # fig.width -> width, fig.height -> height;
            return k.split('fig.', 1)[-1]

        attrs = [(transform_key(k), v)
                 for k, v in attrs.items()
                 if transform_key(k) in image_keys]

        if self.self_contained:
            if 'png' in key:
                data = 'data:image/png;base64,{}'.format(data)
            elif 'svg' in key:
                data = 'data:image/svg+xml;base64,{}'.format(b64_encode(data))
            if 'png' in key or 'svg' in key:
                block = Para([Image([chunk_name, [], attrs],
                                    [Str(caption)],
                                    [data, ""])])
            else:
                raise TypeError("Unknown mimetype %s" % key)
        else:
            # we are saving to filesystem
            ext = mimetypes.guess_extension(key)
            filepath = os.path.join(self.resource_dir,
                                    "{}{}".format(chunk_name, ext))
            os.makedirs(self.resource_dir, exist_ok=True)
            if ext == '.svg':
                with open(filepath, 'wt') as f:
                    f.write(data)
            else:
                with open(filepath, 'wb') as f:
                    f.write(base64.decodebytes(data.encode('utf-8')))
            # Image :: alt text (list of inlines), target
            # Image :: Attr [Inline] Target
            # Target :: (string, string)  of (URL, title)
            block = Para([Image([chunk_name, [], []],
                                [Str(caption)],
                                [filepath, "fig: {}".format(chunk_name)])])

        return block 
开发者ID:pystitch,项目名称:stitch,代码行数:63,代码来源:stitch.py


注:本文中的pandocfilters.Image方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。