pdf - 如何让 Jupyter/IPython Notebook nbconvert 输出不会溢出页面的 PDF?

标签 pdf jupyter-notebook jupyter

当我通过 ipython nbconvert my-notebook.ipynb --to PDF 将 Jupyter/IPython Notebook 转换为 PDF 时,它看起来大部分都不错,除了一些长行和所有输出只是离开页面边缘​​,不会换行。我怎样才能让它停止溢出并换行长行?

最佳答案

我建议使用稍微不同的方法,而不是直接使用终端,而是使用这个带有 GUI 的小 Python 脚本从 Jupyter Notebooks 获取真正高质量的 pdf。它支持语法高亮并且不会弄乱 Latex 或图形。

# Script adapted from CloudCray
# Original Source: https://gist.github.com/CloudCray/994dd361dece0463f64a
# 2016--06-29
# Run this script in the same folder as the notebook(s) you wish to convert
# This will create both an HTML and a PDF file
#
# You'll need wkhtmltopdf (this will keep syntax highlighting, etc)
#   http://wkhtmltopdf.org/downloads.html

import subprocess
import os
from Tkinter import Tk
from tkFileDialog import askopenfilename

WKHTMLTOPDF_PATH = "C:/Program Files/wkhtmltopdf/bin/wkhtmltopdf"  # or wherever you keep it

def export_to_html(filename):
    cmd = 'ipython nbconvert --to html "{0}"'
    subprocess.call(cmd.format(filename), shell=True)
    return filename.replace(".ipynb", ".html")


def convert_to_pdf(filename):
    cmd = '"{0}" "{1}" "{2}"'.format(WKHTMLTOPDF_PATH, filename, filename.replace(".html", ".pdf"))
    subprocess.call(cmd, shell=True)
    return filename.replace(".html", ".pdf")


def export_to_pdf(filename):
    fn = export_to_html(filename)
    return convert_to_pdf(fn)

def main():
    print("Export IPython notebook to PDF")
    print("    Please select a notebook:")

    Tk().withdraw() # Starts in folder from which it is started, keep the root window from appearing 
    x = askopenfilename() # show an "Open" dialog box and return the path to the selected file
    x = str(x.split("/")[-1])

    print(x)

    if not x:
        print("No notebook selected.")
        return 0
    else:
        fn = export_to_pdf(x)
        print("File exported as:\n\t{0}".format(fn))
        return 1

main()

关于pdf - 如何让 Jupyter/IPython Notebook nbconvert 输出不会溢出页面的 PDF?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34485923/

相关文章:

pdf - 为什么在我将 svg 转换为 pdf 时 dominant-baseline 不起作用?

php - 从 PHP Web 应用程序打印客户端报告

javascript - 如何在 jsPDF 库中启用 UTF-8

php - 解析 PDF 文件,并使用 PHP 读取特定部分

python - 名称错误 : name 'boto3' is not defined

python - 打开python文件时如何修复Jupyter扩展激活失败?

python - 是否可以在 nbviewer 中使用 jupyter_contrib_nbextensions?

python - 当我将多个数据帧存储在数据帧列表中并且我记忆起其中一个时,有没有办法格式化输出的列标题?

javascript - IPython 3 到 Jupyter 迁移、custom.js 和事件

ipython - 如何为 Anaconda/Jupyter 设置默认环境?