Debian Codegraph @

examples/services.py

raw symbols SCIP
1 # -*- coding: utf-8 -*-
2 """
3 Example Services for using pypandoc
4 """
5 from tempfile import NamedTemporaryFile
6
7 import pypandoc
8
9
10 class BasePandocService(object):
11 """
12 Base class for converting provided HTML to a doc or docx
13 """
14 file_object = None
15
16 def __init__(self):
17 self.service = self.get_service()
18
19 def get_service(self):
20 return pypandoc
21
22 def generate(self, **kwargs):
23 raise NotImplementedError
24
25
26 class PandocPDFService(BasePandocService):
27 """
28 Generate html to pdf format
29 """
30 def generate(self, html, **kwargs):
31 """
32 generate the pdf but needs to be set as tex so pandoc handles it
33 correctly see docs: http://johnmacfarlane.net/pandoc/ #search pdf
34 """
35 from_format = kwargs.get('from_format', 'html')
36 to_format = kwargs.get('to_format', 'tex')
37 # create temp file
38 self.file_object = NamedTemporaryFile(suffix='.pdf')
39
40 extra_args = (
41 '--smart',
42 '--standalone',
43 '-o', self.file_object.name
44 )
45 # generate it using pandoc
46 self.service.convert_text(html, to_format, format=from_format, extra_args=extra_args)
47 # return the file which is now populated with the docx forms
48 return self.file_object
49
50
51 class PandocDocxService(BasePandocService):
52 """
53 Generate html to docx format
54 """
55 def generate(self, html, **kwargs):
56 from_format = kwargs.get('from_format', 'html')
57 to_format = kwargs.get('to_format', 'docx')
58 # create temp file
59 self.file_object = NamedTemporaryFile(suffix='.docx')
60
61 extra_args = (
62 '--smart',
63 '--standalone',
64 '-o', self.file_object.name
65 )
66 # generate it using pandoc
67 self.service.convert_text(html, to_format, format=from_format, extra_args=extra_args)
68 # return the file which is now populated with the docx forms
69 return self.file_object