將ipynb檔案轉換為pdf
阿新 • • 發佈:2019-02-08
英文
1.安裝python或者安裝miniconda(帶有python)
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開啟執行即可。