##// END OF EJS Templates
add PDFExporter...
MinRK -
Show More
@@ -0,0 +1,141 b''
1 """Export to PDF via latex"""
2
3 # Copyright (c) IPython Development Team.
4 # Distributed under the terms of the Modified BSD License.
5
6 import subprocess
7 import os
8 import sys
9
10 from IPython.utils.traitlets import Integer, List, Bool, Instance
11 from IPython.utils.tempdir import TemporaryWorkingDirectory
12 from .latex import LatexExporter
13
14
15 class PDFExporter(LatexExporter):
16 """Writer designed to write to PDF files"""
17
18 latex_count = Integer(3, config=True,
19 help="How many times latex will be called."
20 )
21
22 latex_command = List([u"pdflatex", u"{filename}"], config=True,
23 help="Shell command used to compile latex."
24 )
25
26 bib_command = List([u"bibtex", u"{filename}"], config=True,
27 help="Shell command used to run bibtex."
28 )
29
30 verbose = Bool(False, config=True,
31 help="Whether to display the output of latex commands."
32 )
33
34 temp_file_exts = List(['.aux', '.bbl', '.blg', '.idx', '.log', '.out'], config=True,
35 help="File extensions of temp files to remove after running."
36 )
37
38 writer = Instance("IPython.nbconvert.writers.FilesWriter", args=())
39
40 def run_command(self, command_list, filename, count, log_function):
41 """Run command_list count times.
42
43 Parameters
44 ----------
45 command_list : list
46 A list of args to provide to Popen. Each element of this
47 list will be interpolated with the filename to convert.
48 filename : unicode
49 The name of the file to convert.
50 count : int
51 How many times to run the command.
52
53 Returns
54 -------
55 success : bool
56 A boolean indicating if the command was successful (True)
57 or failed (False).
58 """
59 command = [c.format(filename=filename) for c in command_list]
60 #In windows and python 2.x there is a bug in subprocess.Popen and
61 # unicode commands are not supported
62 if sys.platform == 'win32' and sys.version_info < (3,0):
63 #We must use cp1252 encoding for calling subprocess.Popen
64 #Note that sys.stdin.encoding and encoding.DEFAULT_ENCODING
65 # could be different (cp437 in case of dos console)
66 command = [c.encode('cp1252') for c in command]
67 times = 'time' if count == 1 else 'times'
68 self.log.info("Running %s %i %s: %s", command_list[0], count, times, command)
69 with open(os.devnull, 'rb') as null:
70 stdout = subprocess.PIPE if not self.verbose else None
71 for index in range(count):
72 p = subprocess.Popen(command, stdout=stdout, stdin=null)
73 out, err = p.communicate()
74 if p.returncode:
75 if self.verbose:
76 # verbose means I didn't capture stdout with PIPE,
77 # so it's already been displayed and `out` is None.
78 out = u''
79 else:
80 out = out.decode('utf-8', 'replace')
81 log_function(command, out)
82 return False # failure
83 return True # success
84
85 def run_latex(self, filename):
86 """Run pdflatex self.latex_count times."""
87
88 def log_error(command, out):
89 self.log.critical(u"%s failed: %s\n%s", command[0], command, out)
90
91 return self.run_command(self.latex_command, filename,
92 self.latex_count, log_error)
93
94 def run_bib(self, filename):
95 """Run bibtex self.latex_count times."""
96 filename = os.path.splitext(filename)[0]
97
98 def log_error(command, out):
99 self.log.warn('%s had problems, most likely because there were no citations',
100 command[0])
101 self.log.debug(u"%s output: %s\n%s", command[0], command, out)
102
103 return self.run_command(self.bib_command, filename, 1, log_error)
104
105 def clean_temp_files(self, filename):
106 """Remove temporary files created by pdflatex/bibtex."""
107 self.log.info("Removing temporary LaTeX files")
108 filename = os.path.splitext(filename)[0]
109 for ext in self.temp_file_exts:
110 try:
111 os.remove(filename+ext)
112 except OSError:
113 pass
114
115 def from_notebook_node(self, nb, resources=None, **kw):
116 latex, resources = super(PDFExporter, self).from_notebook_node(
117 nb, resources=resources, **kw
118 )
119 with TemporaryWorkingDirectory() as td:
120 notebook_name = "notebook"
121 tex_file = self.writer.write(latex, resources, notebook_name=notebook_name)
122 self.log.info("Building PDF")
123 rc = self.run_latex(tex_file)
124 if not rc:
125 rc = self.run_bib(tex_file)
126 if not rc:
127 rc = self.run_latex(tex_file)
128
129 pdf_file = notebook_name + '.pdf'
130 if not os.path.isfile(pdf_file):
131 raise RuntimeError("PDF creating failed")
132 self.log.info('PDF successfully created')
133 with open(pdf_file, 'rb') as f:
134 pdf_data = f.read()
135
136 # convert output extension to pdf
137 # the writer above required it to be tex
138 resources['output_extension'] = 'pdf'
139
140 return pdf_data, resources
141
@@ -4,6 +4,7 b' from .slides import SlidesExporter'
4 4 from .templateexporter import TemplateExporter
5 5 from .latex import LatexExporter
6 6 from .markdown import MarkdownExporter
7 from .pdf import PDFExporter
7 8 from .python import PythonExporter
8 9 from .rst import RSTExporter
9 10 from .exporter import Exporter
@@ -1,17 +1,7 b''
1 """
2 Module containing single call export functions.
3 """
4 #-----------------------------------------------------------------------------
5 # Copyright (c) 2013, the IPython Development Team.
6 #
7 # Distributed under the terms of the Modified BSD License.
8 #
9 # The full license is in the file COPYING.txt, distributed with this software.
10 #-----------------------------------------------------------------------------
1 """Module containing single call export functions."""
11 2
12 #-----------------------------------------------------------------------------
13 # Imports
14 #-----------------------------------------------------------------------------
3 # Copyright (c) IPython Development Team.
4 # Distributed under the terms of the Modified BSD License.
15 5
16 6 from functools import wraps
17 7
@@ -24,6 +14,7 b' from .templateexporter import TemplateExporter'
24 14 from .html import HTMLExporter
25 15 from .slides import SlidesExporter
26 16 from .latex import LatexExporter
17 from .pdf import PDFExporter
27 18 from .markdown import MarkdownExporter
28 19 from .python import PythonExporter
29 20 from .rst import RSTExporter
@@ -79,6 +70,7 b' __all__ = ['
79 70 'export_custom',
80 71 'export_slides',
81 72 'export_latex',
73 'export_pdf',
82 74 'export_markdown',
83 75 'export_python',
84 76 'export_rst',
@@ -134,6 +126,7 b' exporter_map = dict('
134 126 html=HTMLExporter,
135 127 slides=SlidesExporter,
136 128 latex=LatexExporter,
129 pdf=PDFExporter,
137 130 markdown=MarkdownExporter,
138 131 python=PythonExporter,
139 132 rst=RSTExporter,
@@ -1,21 +1,12 b''
1 1 #!/usr/bin/env python
2 """NBConvert is a utility for conversion of .ipynb files.
2 """NbConvert is a utility for conversion of .ipynb files.
3 3
4 4 Command-line interface for the NbConvert conversion utility.
5 5 """
6 #-----------------------------------------------------------------------------
7 #Copyright (c) 2013, the IPython Development Team.
8 #
9 #Distributed under the terms of the Modified BSD License.
10 #
11 #The full license is in the file COPYING.txt, distributed with this software.
12 #-----------------------------------------------------------------------------
13 6
14 #-----------------------------------------------------------------------------
15 #Imports
16 #-----------------------------------------------------------------------------
7 # Copyright (c) IPython Development Team.
8 # Distributed under the terms of the Modified BSD License.
17 9
18 # Stdlib imports
19 10 from __future__ import print_function
20 11
21 12 import logging
@@ -23,7 +14,6 b' import sys'
23 14 import os
24 15 import glob
25 16
26 # From IPython
27 17 from IPython.core.application import BaseIPythonApplication, base_aliases, base_flags
28 18 from IPython.core.profiledir import ProfileDir
29 19 from IPython.config import catch_config_error, Configurable
@@ -128,9 +118,9 b' class NbConvertApp(BaseIPythonApplication):'
128 118
129 119 > ipython nbconvert mynotebook.ipynb --stdout
130 120
131 A post-processor can be used to compile a PDF
121 PDF is generated via latex
132 122
133 > ipython nbconvert mynotebook.ipynb --to latex --post PDF
123 > ipython nbconvert mynotebook.ipynb --to pdf
134 124
135 125 You can get (and serve) a Reveal.js-powered slideshow
136 126
General Comments 0
You need to be logged in to leave comments. Login now