Esempio n. 1
0
    def convert_notebook(cls, nb_path, dest, debug=False, **kwargs):
        warnings.filterwarnings("ignore", r"invalid escape sequence '\\c'",
                                DeprecationWarning)

        options = cls.default_options.copy()
        options.update(kwargs)

        nb = cls.load_notebook(nb_path,
                               filtering=options["filtering"],
                               pagebreaks=options["pagebreaks"])

        if NBCONVERT_6:
            nbconvert.TemplateExporter.extra_template_basedirs = [TEMPLATE_DIR]
            orig_template_name = nbconvert.TemplateExporter.template_name
            nbconvert.TemplateExporter.template_name = options["template"]

        if options["save_tex"]:
            latex_exporter = nbconvert.LatexExporter()
            if not NBCONVERT_6:
                latex_exporter.template_file = os.path.join(
                    TEMPLATE_DIR, options["template"] + ".tpl")

        pdf_exporter = nbconvert.PDFExporter()
        if not NBCONVERT_6:
            pdf_exporter.template_file = os.path.join(
                TEMPLATE_DIR, options["template"] + ".tpl")

        try:
            pdf_output = pdf_exporter.from_notebook_node(nb)
            with open(dest, "wb") as output_file:
                output_file.write(pdf_output[0])

            if options["save_tex"]:
                latex_output = latex_exporter.from_notebook_node(nb)
                with open(os.path.splitext(dest)[0] + ".tex",
                          "w+") as output_file:
                    output_file.write(latex_output[0])

            if NBCONVERT_6:
                nbconvert.TemplateExporter.template_name = orig_template_name

        except nbconvert.pdf.LatexFailed as error:
            print("There was an error generating your LaTeX")
            output = error.output
            if debug:
                print("Showing full error message from PDFTex")

            else:
                print("Showing concise error message")
                output = "\n".join(error.output.split("\n")[-15:])

            print("=" * 60)
            print(output)
            print("=" * 60)

            if NBCONVERT_6:
                nbconvert.TemplateExporter.template_name = orig_template_name
Esempio n. 2
0
def _export_pdf(nb, input_cells=True, execution_counts=True, metadata=dict()):
    # Some display options must be customized in the template, such as author,
    # others are coded into the exporter, such as input cell exclusion.
    template_file = _select_template(execution_counts=execution_counts,
                                     input_cells=input_cells,
                                     **metadata)
    pe = nbconvert.PDFExporter(template_file=template_file)
    pe.exclude_input = not input_cells
    bs, _ = pe.from_notebook_node(nb, dict(metadata=metadata))
    return bs
def nbnode_to_pdf(nb_node, filename="pdfout"):
    """
    function to export a .pdf  file given a notebookNode object as input
    :param nb_node: notebookNode object
    :param filename: str, the name of the output .pdf file. Don't need .pdf extension
    :return: nothing returned, but function will output a new .pdf file
    """
    e = nbconvert.PDFExporter()
    body, resources = e.from_notebook_node(nb_node)
    writer = FilesWriter()
    writer.write(body, resources, notebook_name=filename)
Esempio n. 4
0
def make_pdf_from_ipynb(notebook_file):
    remove_pdf_link_ipynb(notebook_file)
    exporter = nbconvert.PDFExporter()
    nb = nbformat.read(notebook_file, 4)
    firstcell = nb["cells"][0]
    nb["cells"][0] = extract_title_ipynb(nb["cells"][0])
    pdf, resources = exporter.from_notebook_node(nb)
    outfile = "content/images/" + os.path.basename(notebook_file).split(
        ".")[0] + ".pdf"
    with open(outfile, "wb") as tp:
        tp.write(pdf)
    add_link_to_pdf_ipynb(notebook_file)
Esempio n. 5
0
def generate_gradable_pdf(input_notebook: nbformat.NotebookNode,
                          pdf_path: str,
                          gradable_tag='gradable'):
    filtered_notebook = filter_cells(
        input_notebook,
        lambda cell: gradable_tag in cell.metadata.get('tags', []))

    exporter = nbconvert.PDFExporter(config={})
    exporter.exclude_input_prompt = True
    exported_pdf, _ = exporter.from_notebook_node(
        nb=filtered_notebook,
        resources={'metadata': {
            'name': 'Something normal'
        }})

    with open(pdf_path, 'wb') as f:
        f.write(exported_pdf)
Esempio n. 6
0
def convert_notebook_to_pdf(model, template_file='report.tplx', log_level=None):
  config = _get_config(default={
    'TagRemovePreprocessor': {
      'remove_all_outputs_tags': {"hide_output"},
      'remove_input_tags': {"hide_input"},
      'remove_cell_tags': {"hide_all"}
    }
  })

  # Get the location of the report template and add that path to the exporter's
  # template_path list
  root_dir = os.path.dirname(os.path.abspath(__file__))
  templates_dir = os.path.join(root_dir, 'templates')
  config['Exporter']['template_path'].append(templates_dir)
  exporter = nbconvert.PDFExporter(config)
  exporter.template_file = template_file if template_file is not None else DEFAULT_TEMPLATE
  # Hide input and output prompts (e.g., In [32]: ) from the exported content
  # For some reason, setting exclude_input_prompt = True is causing the
  # newlines in the code to dissapear. This appears to be a bug in nbconvert.
  # exporter.exclude_input_prompt = True
  # exporter.exclude_output_prompt = True
  if log_level is not None:
    exporter.log.setLevel(log_level)
    exporter.propagate = False
    handler = logging.StreamHandler()
    handler.setLevel(log_level)
    exporter.log.addHandler(handler)

  notebook = nbformat.notebooknode.from_dict(model['content'])
  notebook = _append_cell_contents(notebook)
  notebook_name = os.path.splitext(model.get('name', 'Notebook'))[0]
  # For some reason the from_notebook_node function does not bother to use the
  # notebook's metadata, so we need to extract it from the notebook, add it to
  # the resources dict, and pass it in directly.
  resources = nbconvert.exporters.exporter.ResourcesDict()
  resources['metadata'] = dict({'name': notebook_name}, **notebook['metadata'])

  (body, resources) = exporter.from_notebook_node(notebook, resources)

  return body
Esempio n. 7
0
def nbnode_to_pdf(nb_node, filename="pdfout"):
    e = nbconvert.PDFExporter()
    body, resources = e.from_notebook_node(nb_node)
    writer = FilesWriter()
    writer.write(body, resources, notebook_name=filename)