将ipynb文件转换为pdf

英文

1.安装python或者安装miniconda(带有python)

2.安装MiKTeX :https://miktex.org/download

3.利用conda命令安装 Jupyter

运行:

jupyter notebook

会将当前目录下的文件加载到浏览器本地网站目录下(确保.ipynb文件也在当前目录下),然后在网站上点开如00.ipynb。

这里写图片描述

但是上面的方式只能保存英文,中文好像不可以。

中文

下面我们使用文献1中的方法,当然也要确保上面的都安装好。

ipynb2pdf.py:

# coding:utf-8
import sys
import os
import re
import shutil
notebook = sys.argv[1]
texFile = notebook.replace('.ipynb','.tex')
# 1.convert .ipynb to latex file .tex
# 将ipynb文件转为tex文件
print '1. convert ' + notebook + ' to ' + texFile  
print '------ \n'
os.system(r'jupyter nbconvert --to latex ' + notebook)
print 'convert over'
# 2. add Chinese support by adding the string below
# 加入引用的包使支持中文(直接转换中文会丢失)
# \usepackage{fontspec, xunicode, xltxtra}
# \setmainfont{Microsoft YaHei} 
# \usepackage{ctex}
print '2. add Chinese support to .tex file' 
print '------'
file = open(texFile,'r')
str_file = file.read()
strinfo = re.compile('(documentclass[\d\D]+\{article\})')  #查找的字符line0
m=re.findall(strinfo,str_file)
if len(m) == 0:
    print r'can not find documentclass[**pt]{article}'
    sys.exit(1)
str_file = strinfo.sub('\\1 \n \\usepackage{fontspec, xunicode, xltxtra} \n \\setmainfont{Microsoft YaHei} \r \\usepackage{ctex}',str_file)  #  替换的字符line1
file.close()
file = open(texFile,'w')
file.write(str_file)
file.close()
print 'add Chinese support successed'
# 3. convert .tex to .pdf by xelatex
# 使用xelatex命令编译.tex文件得到pdf
print  '3. convert tex to pdf'
print '------'
os.system('xelatex ' + texFile)
print  'convert pdf successed'
# 4. delete the auxiliary files
# 清理生成的中间文件
# change there if latex file is needed
print '4. delete auxiliary files'
print '------'
os.remove(notebook.replace('.ipynb','.aux'))
os.remove(notebook.replace('.ipynb','.log'))
os.remove(notebook.replace('.ipynb','.out'))
# change there if latex file is needed
os.remove(notebook.replace('.ipynb','.tex'))
if os.path.isdir(notebook.replace('.ipynb','_files')):
    shutil.rmtree(notebook.replace('.ipynb','_files'))
print 'delete auxiliary files successed'

将上面的文件ipynb2pdf.py拷贝到python.exe文件所在目录,同时需要转换的00.ipynb也在此目录(我们用的相对路径),利用下面的指令:

python ipynb2pdf.py 00.ipynb

此过程MiKTeX可能会自动下载所需要的包,最后可以在同目录下生成00.pdf文件。

手动将.ipynb 转换为latex,然后再转换为pdf

利用上面的方法转换的pdf格式是默认的,例如是A4大小,有些代码可能显示不出来,我们需要将纸张的大小设置为A3的,但是自己又不会修改上面的代码,因此可以先转换为latex,然后利用texlive或者MiKTeX ,打开latex文件,自己在上面修改纸张的大小,如:

\documentclass[11pt,a3paper]{article}

具体转换如下:

1.将.ipynb转换为.tex

jupyter-nbconvert --to latex 00.ipynb

编辑生成的.tex文件,添加支持中文:

  \usepackage{fontspec, xunicode, xltxtra} 
  \setmainfont{Microsoft YaHei} 
  \usepackage{ctex}

2 将.tex 转换为pdf
即利用texlive或者MiKTeX打开运行即可。

参考文献:
1.http://www.cnblogs.com/fly2wind/p/6294831.html [直接执行的python代码ipynb2pdf.py]

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值