PDFTemplate.py 10.6 KB
Newer Older
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1 2 3
##############################################################################
#
# Copyright (c) 2002 Nexedi SARL and Contributors. All Rights Reserved.
Jean-Paul Smets's avatar
Jean-Paul Smets committed
4
#                    Jean-Paul Smets-Solanes <jp@nexedi.com>
Jean-Paul Smets's avatar
Jean-Paul Smets committed
5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34
#
# WARNING: This program as such is intended to be used by professional
# programmers who take the whole responsability of assessing all potential
# consequences resulting from its eventual inadequacies and bugs
# End users who are looking for a ready-to-use solution with commercial
# garantees and support are strongly adviced to contract a Free Software
# Service Company
#
# This program is Free Software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
#
##############################################################################

from Products.CMFCore.utils import getToolByName
from Products.CMFCore.FSPageTemplate import FSPageTemplate
from Products.CMFCore.DirectoryView import registerFileExtension, registerMetaType
from Products.Formulator.Form import BasicForm
from Products.Formulator.Form import fields
from Products.PageTemplates.ZopePageTemplate import ZopePageTemplate
35
from Products.PageTemplates.PageTemplateFile import PageTemplateFile
Jean-Paul Smets's avatar
Jean-Paul Smets committed
36 37 38 39 40
from Products.ERP5Type import PropertySheet

from urllib import quote
from Globals import InitializeClass, PersistentMapping, DTMLFile, get_request
from AccessControl import Unauthorized, getSecurityManager, ClassSecurityInfo
41
import urllib2
Jean-Paul Smets's avatar
Jean-Paul Smets committed
42 43 44 45 46

from Products.ERP5Type.Utils import UpperCase

from zLOG import LOG

47 48 49 50 51 52 53
try:
    from webdav.Lockable import ResourceLockedError
    from webdav.WriteLockInterface import WriteLockInterface
    SUPPORTS_WEBDAV_LOCKS = 1
except ImportError:
    SUPPORTS_WEBDAV_LOCKS = 0

Jean-Paul Smets's avatar
Jean-Paul Smets committed
54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115
# Constructors
manage_addPDFTemplate = DTMLFile("dtml/PDFTemplate_add", globals())

def addPDFTemplate(self, id, title="", REQUEST=None):
    """Add form to folder.
    id     -- the id of the new form to add
    title  -- the title of the form to add
    Result -- empty string
    """
    # add actual object
    id = self._setObject(id, PDFTemplate(id, title))
    # respond to the add_and_edit button if necessary
    add_and_edit(self, id, REQUEST)
    return ''

def add_and_edit(self, id, REQUEST):
    """Helper method to point to the object's management screen if
    'Add and Edit' button is pressed.
    id -- id of the object we just added
    """
    if REQUEST is None:
        return
    try:
        u = self.DestinationURL()
    except:
        u = REQUEST['URL1']
    if REQUEST['submit'] == " Add and Edit ":
        u = "%s/%s" % (u, quote(id))
    REQUEST.RESPONSE.redirect(u+'/manage_main')


class PDFTemplate(ZopePageTemplate):
    """
        A Formulator form with a built-in rendering parameter based
        on page templates or DTML.
    """
    meta_type = "ERP5 PDF Template"
    icon = "www/PDF.png"

    # Declarative Security
    security = ClassSecurityInfo()

    # Declarative properties
    property_sheets = ( PropertySheet.Base
                      , PropertySheet.SimpleItem)

    # Constructors
    constructors =   (manage_addPDFTemplate, addPDFTemplate)

    # Default Attributes
    pdf_stylesheet = 'default_pdf_template'
    content_type = 'application/pdf'

    # Management interface
    manage_options =  ( ZopePageTemplate.manage_options +
        (
          {'label':'Stylesheet Setting', 'action':'formSettings',
           'help':('ERPForm', 'pdfStylesheet.txt')},
        )
      )

    security.declareProtected('View management screens', 'formSettings')
116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133
    formSettings = PageTemplateFile('www/formSettings', globals(), __name__='formSettings')
    formSettings._owner = None

    security.declareProtected('Change Page Templates', 'doSettings')
    def doSettings(self, REQUEST, title, pdf_stylesheet):
      """
        Change title and pdf_stylesheet.
      """
      if SUPPORTS_WEBDAV_LOCKS and self.wl_isLocked():
        raise ResourceLockedError, "File is locked via WebDAV"
      self.pdf_stylesheet = pdf_stylesheet
      self.pt_setTitle(title)
      #REQUEST.set('text', self.read()) # May not equal 'text'!
      message = "Saved changes."
      if getattr(self, '_v_warnings', None):
        message = ("<strong>Warning:</strong> <i>%s</i>"
                  % '<br>'.join(self._v_warnings))
      return self.formSettings(manage_tabs_message=message)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
134 135

    # Proxy method to PageTemplate
136 137
    def pt_render(self, source=0, extra_context={}):
      doc_xml = ZopePageTemplate.pt_render(self, source=source, extra_context=extra_context)
138

139
      # Unmarshall arguments to __call__ API
140
      args = extra_context.get('options', None)
141 142 143 144 145 146 147
      kwargs = extra_context.copy()
      if kwargs.has_key('options'): del kwargs['options']
      if kwargs.has_key('context'): del kwargs['context']

      batch_mode = extra_context.get('batch_mode', 0)

      request = extra_context.get('REQUEST', None)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
148 149 150 151 152 153 154 155
      if not request:
        request = get_request()

      if request.get('debug',0):
        return doc_xml

      report_tool = getToolByName(self, 'portal_report')
      pdf = report_tool.renderPDF(self.pdf_stylesheet, doc_xml, context=self.pt_getContext()['here'], *args, **kwargs)
156
      if request and not batch_mode:
Jean-Paul Smets's avatar
Jean-Paul Smets committed
157 158 159 160 161 162 163 164 165 166
        request.RESPONSE.setHeader('Content-Type','application/pdf')
        request.RESPONSE.setHeader('Content-Length',len(pdf))
        request.RESPONSE.setHeader('Content-Disposition','inline;filename=%s.pdf' % self.id)

      return pdf

    #def _exec(self, bound_names, args, kw):
    #    pt = getattr(self,self.pt)
    #    return pt._exec(self, bound_names, args, kw)

167 168 169 170 171 172 173 174 175 176 177 178 179
    def om_icons(self):
        """Return a list of icon URLs to be displayed by an ObjectManager"""
        icons = ({'path': 'misc_/ERP5Form/PDF.png',
                  'alt': self.meta_type, 'title': self.meta_type},)
        if not self._v_cooked:
            self._cook()
        if self._v_errors:
            icons = icons + ({'path': 'misc_/PageTemplates/exclamation.gif',
                              'alt': 'Error',
                              'title': 'This template has an error'},)
        return icons


Jean-Paul Smets's avatar
Jean-Paul Smets committed
180 181 182 183 184 185 186 187 188 189 190 191
InitializeClass(PDFTemplate)

class FSPDFTemplate(FSPageTemplate, PDFTemplate):

    meta_type = "ERP5 Filesystem PDF Template"
    icon = "www/PDF.png"

    def __call__(self, *args, **kwargs):
      return PDFTemplate.__call__(self, *args, **kwargs)

InitializeClass(FSPDFTemplate)

192
registerFileExtension('pdft', FSPDFTemplate)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
193 194 195
registerMetaType('ERP5 PDF Template', FSPDFTemplate)

# Dynamic Patch
196 197 198 199 200 201 202 203
from Products.CMFReportTool.ReportTool import ReportTool
try:
  from Products.CMFReportTool.ReportTool import ZODBResourceHandler
  HAS_ZODB_RESOURCE_HANDLER=1
except ImportError:
  from Products.CMFReportTool.ReportTool import ZODBHandler, ResourceHandler
  HAS_ZODB_RESOURCE_HANDLER=0

Jean-Paul Smets's avatar
Jean-Paul Smets committed
204 205 206 207 208 209 210
from Products.CMFReportTool.RenderPDF.Parser import TemplateParser,DocumentParser
from Products.PageTemplates.Expressions import restrictedTraverse
from StringIO import StringIO
import xml.dom.minidom
import urllib,os.path


211 212 213 214 215 216 217 218 219 220
if HAS_ZODB_RESOURCE_HANDLER:
  class ERP5ResourceHandler(ZODBResourceHandler):
    ''' Wrapper for ZODB Resources and files'''

    def handleZODB(self,path):

      path = path.split('/')
      obj = restrictedTraverse(self.context,path,getSecurityManager())

      # check type and e.g. call object if script ...
221 222 223 224 225
      if callable(obj):
        try:
          obj = obj()
        except:
          pass
226 227 228

      ## for OFS.Image-like objects
      if hasattr(obj,'_original'):
229
        obj = obj._original._data()
230 231 232 233 234 235 236 237 238 239 240 241
      elif hasattr(obj,'_data'):
        obj = obj._data
      elif hasattr(obj,'data'):
        obj = obj.data

      return StringIO(str(obj))
else:
  class ERP5ResourceHandler(ResourceHandler):
    ''' Wrapper for ZODB Resources and files'''
    def __init__(self, context=None, resource_path=None):
        zodbhandler = ERP5ZODBHandler(context)
        self.opener = urllib2.build_opener(zodbhandler)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
242

243 244 245 246 247
  class ERP5ZODBHandler(ZODBHandler):
    def zodb_open(self, req):
      path = req.get_selector()
      path = path.split('/')
      obj = restrictedTraverse(self.context,path,getSecurityManager())
Jean-Paul Smets's avatar
Jean-Paul Smets committed
248

249
      # check type and e.g. call object if script ...
250 251 252 253 254
      if callable(obj):
        try:
          obj = obj()
        except:
          pass
Jean-Paul Smets's avatar
Jean-Paul Smets committed
255

256 257
      ## for OFS.Image-like objects
      if hasattr(obj,'_original'):
258
        obj = obj._original._data()
259 260 261 262
      elif hasattr(obj,'_data'):
        obj = obj._data
      elif hasattr(obj,'data'):
        obj = obj.data
Jean-Paul Smets's avatar
Jean-Paul Smets committed
263

264
      return StringIO(str(obj))
Jean-Paul Smets's avatar
Jean-Paul Smets committed
265 266 267 268 269 270 271 272 273 274



class ERP5ReportTool(ReportTool):

  def renderPDF(self, templatename, document_xml, *args, **kwargs):
    """
      Render document using template
    """

275 276 277 278
    context = kwargs.get('context',None)
    if context is None:
      context = self

279
    encoding = kwargs.get('encoding') or 'UTF-8'
280
    #LOG('ERP5ReportTool', 0, 'encoding = %r' % encoding)
281
    rhandler = ERP5ResourceHandler(context, getattr(self, 'resourcePath', None))
Jean-Paul Smets's avatar
Jean-Paul Smets committed
282

283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302
    # if zope gives us the xml in unicode
    # we need to encode it before it can be parsed
    template_xml = getattr(context, templatename)(*args, **kwargs)
    if type(template_xml) is type(u''):
      template_xml = self._encode(template_xml, encoding)
    if type(document_xml) is type(u''):
      document_xml = self._encode(document_xml, encoding)
    #LOG('ERP5ReportTool', 0, 'template_xml = %r, document_xml = %r' % (template_xml, document_xml))

    # XXXXX Because reportlab does not support UTF-8, use Latin-1. What a mess.
    template_xml = unicode(template_xml,encoding).encode('iso-8859-1')
    document_xml = unicode(document_xml,encoding).encode('iso-8859-1')
    encoding = 'iso-8859-1'

    # create the PDFTemplate from xml
    template_dom = xml.dom.minidom.parseString(template_xml)
    template_dom.encoding = encoding
    template = TemplateParser(template_dom,encoding,resourceHandler=rhandler)()

    # create the PDFDocment from xml
Jean-Paul Smets's avatar
Jean-Paul Smets committed
303
    document_dom = xml.dom.minidom.parseString(document_xml)
304
    document_dom.encoding = encoding
Jean-Paul Smets's avatar
Jean-Paul Smets committed
305 306
    document = DocumentParser(document_dom,encoding,resourceHandler=rhandler)

307
    # create the PDF itself using the document and the template
Jean-Paul Smets's avatar
Jean-Paul Smets committed
308 309 310 311 312 313 314
    buf = StringIO()
    document(template,buf)
    buf.seek(0)
    return buf.read()


ReportTool.renderPDF = ERP5ReportTool.renderPDF