1 # -*- coding: utf-8 -*-
2 ##############################################################################
4 # Copyright (c) 2010 Camptocamp SA (http://www.camptocamp.com)
7 # Author : Nicolas Bessi (Camptocamp)
9 # WARNING: This program as such is intended to be used by professional
10 # programmers who take the whole responsability of assessing all potential
11 # consequences resulting from its eventual inadequacies and bugs
12 # End users who are looking for a ready-to-use solution with commercial
13 # garantees and support are strongly adviced to contract a Free Software
16 # This program is Free Software; you can redistribute it and/or
17 # modify it under the terms of the GNU General Public License
18 # as published by the Free Software Foundation; either version 2
19 # of the License, or (at your option) any later version.
21 # This program is distributed in the hope that it will be useful,
22 # but WITHOUT ANY WARRANTY; without even the implied warranty of
23 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
24 # GNU General Public License for more details.
26 # You should have received a copy of the GNU General Public License
27 # along with this program; if not, write to the Free Software
28 # Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
30 ##############################################################################
38 from mako.template import Template
39 from mako import exceptions
42 from report_helper import WebKitHelper
43 from report.report_sxw import *
45 from tools.translate import _
46 from osv.osv import except_osv
48 class WebKitParser(report_sxw):
49 """Custom class that use webkit to render HTML reports
50 Code partially taken from report openoffice. Thanks guys :)
53 def __init__(self, name, table, rml=False, parser=False,
54 header=True, store=False):
55 self.parser_instance = False
57 report_sxw.__init__(self, name, table, rml, parser,
60 def get_lib(self, cursor, uid, company) :
61 """Return the lib wkhtml path"""
62 #TODO Detect lib in system first
63 path = self.pool.get('res.company').read(cursor, uid, company, ['lib_path',])
64 path = path['lib_path']
67 _('Wkhtmltopdf library path is not set in company'),
68 _('Please install executable on your system'+
69 ' (sudo apt-get install wkhtmltopdf) or download it from here:'+
70 ' http://code.google.com/p/wkhtmltopdf/downloads/list and set the'+
71 ' path to the executable on the Company form.')
73 if os.path.isabs(path) :
74 if (os.path.exists(path) and os.access(path, os.X_OK)\
75 and os.path.basename(path).startswith('wkhtmltopdf')):
79 _('Wrong Wkhtmltopdf path set in company'+
80 'Given path is not executable or path is wrong'),
85 _('path to Wkhtmltopdf is not absolute'),
88 def generate_pdf(self, comm_path, report_xml, header, footer, html_list, webkit_header=False):
89 """Call webkit in order to generate pdf"""
91 webkit_header = report_xml.webkit_header
92 tmp_dir = tempfile.gettempdir()
93 out = report_xml.name+str(time.time())+'.pdf'
94 out = os.path.join(tmp_dir, out.replace(' ',''))
100 command = ['wkhtmltopdf']
104 head_file = file( os.path.join(
106 str(time.time()) + '.head.html'
110 head_file.write(header)
112 file_to_del.append(head_file.name)
113 command.extend(['--header-html', head_file.name])
115 foot_file = file( os.path.join(
117 str(time.time()) + '.foot.html'
121 foot_file.write(footer)
123 file_to_del.append(foot_file.name)
124 command.extend(['--footer-html', foot_file.name])
126 if webkit_header.margin_top :
127 command.extend(['--margin-top', str(webkit_header.margin_top).replace(',', '.')])
128 if webkit_header.margin_bottom :
129 command.extend(['--margin-bottom', str(webkit_header.margin_bottom).replace(',', '.')])
130 if webkit_header.margin_left :
131 command.extend(['--margin-left', str(webkit_header.margin_left).replace(',', '.')])
132 if webkit_header.margin_right :
133 command.extend(['--margin-right', str(webkit_header.margin_right).replace(',', '.')])
134 if webkit_header.orientation :
135 command.extend(['--orientation', str(webkit_header.orientation).replace(',', '.')])
136 if webkit_header.format :
137 command.extend(['--page-size', str(webkit_header.format).replace(',', '.')])
139 for html in html_list :
140 html_file = file(os.path.join(tmp_dir, str(time.time()) + str(count) +'.body.html'), 'w')
142 html_file.write(html)
144 file_to_del.append(html_file.name)
145 command.append(html_file.name)
147 generate_command = ' '.join(command)
149 status = subprocess.call(command, stderr=subprocess.PIPE) # ignore stderr
152 _('Webkit raise an error' ),
156 for f_to_del in file_to_del :
159 pdf = file(out, 'rb').read()
160 for f_to_del in file_to_del :
167 def setLang(self, lang):
170 self.localcontext['lang'] = lang
172 def translate_call(self, src):
173 """Translate String."""
174 ir_translation = self.pool.get('ir.translation')
175 res = ir_translation._get_source(self.parser_instance.cr, self.parser_instance.uid, self.name, 'report', self.localcontext.get('lang', 'en_US'), src)
180 def formatLang(self, value, digits=None, date=False, date_time=False, grouping=True, monetary=False):
181 """format using the know cursor, language from localcontext"""
183 digits = self.parser_instance.get_digits(value)
184 if isinstance(value, (str, unicode)) and not value:
186 pool_lang = self.pool.get('res.lang')
187 lang = self.localcontext['lang']
189 lang_ids = pool_lang.search(self.parser_instance.cr, self.parser_instance.uid, [('code','=',lang)])[0]
190 lang_obj = pool_lang.browse(self.parser_instance.cr, self.parser_instance.uid, lang_ids)
192 if date or date_time:
196 date_format = lang_obj.date_format
197 parse_format = '%Y-%m-%d'
199 value=value.split('.')[0]
200 date_format = date_format + " " + lang_obj.time_format
201 parse_format = '%Y-%m-%d %H:%M:%S'
202 if not isinstance(value, time.struct_time):
203 return time.strftime(date_format, time.strptime(value, parse_format))
206 date = datetime(*value.timetuple()[:6])
207 return date.strftime(date_format)
209 return lang_obj.format('%.' + str(digits) + 'f', value, grouping=grouping, monetary=monetary)
211 # override needed to keep the attachments' storing procedure
212 def create_single_pdf(self, cursor, uid, ids, data, report_xml, context=None):
213 """generate the PDF"""
218 if report_xml.report_type != 'webkit':
219 return super(WebKitParser,self).create_single_pdf(cursor, uid, ids, data, report_xml, context=context)
221 self.parser_instance = self.parser(
228 self.pool = pooler.get_pool(cursor.dbname)
229 objs = self.getObjects(cursor, uid, ids, context)
230 self.parser_instance.set_context(objs, data, ids, report_xml.report_type)
234 if report_xml.report_file :
235 path = addons.get_module_resource(report_xml.report_file)
236 if os.path.exists(path) :
237 template = file(path).read()
238 if not template and report_xml.report_webkit_data :
239 template = report_xml.report_webkit_data
241 raise except_osv(_('Error!'), _('Webkit Report template not found !'))
242 header = report_xml.webkit_header.html
243 footer = report_xml.webkit_header.footer_html
244 if not header and report_xml.header:
246 _('No header defined for this Webkit report!'),
247 _('Please set a header in company settings')
249 if not report_xml.header :
250 #I know it could be cleaner ...
254 <style type="text/css">
260 var x=document.location.search.substring(1).split('&');
261 for(var i in x) {var z=x[i].split('=',2);vars[z[0]] = unescape(z[1]);}
262 var x=['frompage','topage','page','webpage','section','subsection','subsubsection'];
264 var y = document.getElementsByClassName(x[i]);
265 for(var j=0; j<y.length; ++j) y[j].textContent = vars[x[i]];
270 <body style="border:0; margin: 0;" onload="subst()">
273 css = report_xml.webkit_header.css
276 user = self.pool.get('res.users').browse(cursor, uid, uid)
277 company= user.company_id
279 #default_filters=['unicode', 'entity'] can be used to set global filter
280 body_mako_tpl = Template(template ,input_encoding='utf-8')
281 helper = WebKitHelper(cursor, uid, report_xml.id, context)
283 html = body_mako_tpl.render( helper=helper,
285 _=self.translate_call,
286 **self.parser_instance.localcontext
289 msg = exceptions.text_error_template().render()
290 netsvc.Logger().notifyChannel('Webkit render', netsvc.LOG_ERROR, msg)
291 raise except_osv(_('Webkit render'), msg)
292 head_mako_tpl = Template(header, input_encoding='utf-8')
294 head = head_mako_tpl.render(
299 formatLang=self.formatLang,
300 setLang=self.setLang,
301 _=self.translate_call,
305 raise except_osv(_('Webkit render'),
306 exceptions.text_error_template().render())
309 foot_mako_tpl = Template(footer ,input_encoding='utf-8')
311 foot = foot_mako_tpl.render(
316 formatLang=self.formatLang,
317 setLang=self.setLang,
318 _=self.translate_call,
321 msg = exceptions.text_error_template().render()
322 netsvc.Logger().notifyChannel('Webkit render', netsvc.LOG_ERROR, msg)
323 raise except_osv(_('Webkit render'), msg)
324 if report_xml.webkit_debug :
326 deb = head_mako_tpl.render(
332 formatLang=self.formatLang,
333 setLang=self.setLang,
334 _=self.translate_call,
337 msg = exceptions.text_error_template().render()
338 netsvc.Logger().notifyChannel('Webkit render', netsvc.LOG_ERROR, msg)
339 raise except_osv(_('Webkit render'), msg)
341 bin = self.get_lib(cursor, uid, company.id)
342 pdf = self.generate_pdf(bin, report_xml, head, foot, [html])
346 def create(self, cursor, uid, ids, data, context=None):
347 """We override the create function in order to handle generator
348 Code taken from report openoffice. Thanks guys :) """
349 pool = pooler.get_pool(cursor.dbname)
350 ir_obj = pool.get('ir.actions.report.xml')
351 report_xml_ids = ir_obj.search(cursor, uid,
352 [('report_name', '=', self.name[7:])], context=context)
355 report_xml = ir_obj.browse(
361 report_xml.report_rml = None
362 report_xml.report_rml_content = None
363 report_xml.report_sxw_content_data = None
364 report_rml.report_sxw_content = None
365 report_rml.report_sxw = None
367 return super(WebKitParser, self).create(cursor, uid, ids, data, context)
368 if report_xml.report_type != 'webkit' :
369 return super(WebKitParser, self).create(cursor, uid, ids, data, context)
370 result = self.create_source_pdf(cursor, uid, ids, data, report_xml, context)