首页 > 代码库 > 简单python脚本,将jupter notebook的ipynb文件转为pdf(包含中文)

简单python脚本,将jupter notebook的ipynb文件转为pdf(包含中文)

直接执行的python代码ipynb2pdf.py

  1. # coding:utf-8
  2. import sys
  3. import os
  4. import re
  5. import shutil
  6. notebook = sys.argv[1]
  7. texFile = notebook.replace(‘.ipynb‘,‘.tex‘)
  8. # 1.convert .ipynb to latex file .tex
  9. # 将ipynb文件转为tex文件
  10. print ‘1. convert ‘ + notebook + ‘ to ‘ + texFile
  11. print ‘------ \n‘
  12. os.system(r‘jupyter nbconvert --to latex ‘ + notebook)
  13. print ‘convert over‘
  14. # 2. add Chinese support by adding the string below
  15. # 加入引用的包使支持中文(直接转换中文会丢失)
  16. # \usepackage{fontspec, xunicode, xltxtra}
  17. # \setmainfont{Microsoft YaHei}
  18. # \usepackage{ctex}
  19. print ‘2. add Chinese support to .tex file‘
  20. print ‘------‘
  21. file = open(texFile,‘r‘)
  22. str_file = file.read()
  23. strinfo = re.compile(‘(documentclass[\d\D]+\{article\})‘) #查找的字符line0
  24. m=re.findall(strinfo,str_file)
  25. if len(m) == 0:
  26. print r‘can not find documentclass[**pt]{article}‘
  27. sys.exit(1)
  28. str_file = strinfo.sub(‘\\1 \n \\usepackage{fontspec, xunicode, xltxtra} \n \\setmainfont{Microsoft YaHei} \r \\usepackage{ctex}‘,str_file) # 替换的字符line1
  29. file.close()
  30. file = open(texFile,‘w‘)
  31. file.write(str_file)
  32. file.close()
  33. print ‘add Chinese support successed‘
  34. # 3. convert .tex to .pdf by xelatex
  35. # 使用xelatex命令编译.tex文件得到pdf
  36. print ‘3. convert tex to pdf‘
  37. print ‘------‘
  38. os.system(‘xelatex ‘ + texFile)
  39. print ‘convert pdf successed‘
  40. # 4. delete the auxiliary files
  41. # 清理生成的中间文件
  42. # change there if latex file is needed
  43. print ‘4. delete auxiliary files‘
  44. print ‘------‘
  45. os.remove(notebook.replace(‘.ipynb‘,‘.aux‘))
  46. os.remove(notebook.replace(‘.ipynb‘,‘.log‘))
  47. os.remove(notebook.replace(‘.ipynb‘,‘.out‘))
  48. # change there if latex file is needed
  49. os.remove(notebook.replace(‘.ipynb‘,‘.tex‘))
  50. if os.path.isdir(notebook.replace(‘.ipynb‘,‘_files‘)):
  51. shutil.rmtree(notebook.replace(‘.ipynb‘,‘_files‘))
  52. 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



null


简单python脚本,将jupter notebook的ipynb文件转为pdf(包含中文)