Skip to content

Commit

Permalink
allow for binary base64 encoding
Browse files Browse the repository at this point in the history
  • Loading branch information
maartenbreddels committed Oct 15, 2019
1 parent 5cc4913 commit 3847c1c
Showing 1 changed file with 20 additions and 3 deletions.
23 changes: 20 additions & 3 deletions nbconvert/exporters/html.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
from traitlets.config import Config
from jupyter_core.paths import jupyter_path
from jinja2 import contextfilter
from jinja2.loaders import split_template_path
import jinja2

from nbconvert.filters.highlight import Highlight2HTML
Expand Down Expand Up @@ -112,10 +113,26 @@ def resources_include_js(name):
def resources_include_url(name):
env = self.environment
mime_type, encoding = mimetypes.guess_type(name)
data = env.loader.get_source(env, name)[0]
data = base64.b64encode(data.encode('utf8'))
try:
# we try to load via the jinja loader, but that tries to load
# as (encoded) text
data = env.loader.get_source(env, name)[0].encode('utf8')
except UnicodeDecodeError:
# if that fails (for instance a binary file, png or ttf)
# we mimic jinja2
pieces = split_template_path(name)
searchpaths = self.get_template_paths()
for searchpath in searchpaths:
filename = os.path.join(searchpath, *pieces)
print(filename, os.path.exists(filename))
if os.path.exists(filename):
with open(filename, "rb") as f:
data = f.read()
break
else:
raise ValueError("No file %r found in %r" % (name, searchpaths))
data = base64.b64encode(data)
data = data.replace(b'\n', b'').decode('ascii')
print(type(data), data)
src = 'data:{mime_type};base64,{data}'.format(mime_type=mime_type, data=data)
return jinja2.Markup(src)
resources = super(HTMLExporter, self)._init_resources(resources)
Expand Down

0 comments on commit 3847c1c

Please sign in to comment.