简单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





转载于:https://www.cnblogs.com/fly2wind/p/6294831.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值