本文整理匯總了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
示例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, ""])])
示例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, ""])])
示例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).
示例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])])
示例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])])
示例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), ""])])
示例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])
示例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
示例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
示例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)
),
""
])])
示例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