簡單python腳本,將jupter notebook的ipynb文件轉為pdf(包含中文)


直接執行的python代碼ipynb2pdf.py

主要思路。將ipynb文件轉成tex文件,然后使用latex編譯成pdf。由於latex默認轉換不顯示中文,需要向tex文件中添加相關中文包。

依賴 latex 中的 xelatex,需要xelatex.exe文件在PATH環境變量下

# 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'

 

調用方式

  1. 在當前目錄中打開命令行(目錄中要有ipynb2pdf.py 與 .ipynb文件)
  2. 輸入命令
    python ipynb2pdf.py yourFilename.ipynb

打包為exe(可以忽略)

使用pyinstaller打包為exe,作為命令行命令
pyinstaller -F ipynb2pdf.py
生成的exe放入系統path目錄的文件夾下即可直接通過命令的形式處理

調用時在.ipynb所在的文件夾下打開命令行,輸入命令
ipynb2pdf yourFilename.ipynb






免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM