Commit ec783b49 authored by Jérome Perrin's avatar Jérome Perrin

fix indentation


git-svn-id: https://svn.erp5.org/repos/public/erp5/trunk@3674 20353a03-c40f-0410-a6d1-a30d3c3de9de
parent 3679cdcf
...@@ -43,10 +43,10 @@ import types, popen2, os ...@@ -43,10 +43,10 @@ import types, popen2, os
from tempfile import mktemp from tempfile import mktemp
try: try:
from webdav.Lockable import ResourceLockedError from webdav.Lockable import ResourceLockedError
SUPPORTS_WEBDAV_LOCKS = 1 SUPPORTS_WEBDAV_LOCKS = 1
except ImportError: except ImportError:
SUPPORTS_WEBDAV_LOCKS = 0 SUPPORTS_WEBDAV_LOCKS = 0
# FIXME: Programs linked against mandriva libgcj v 3.4.0 ave a strange # FIXME: Programs linked against mandriva libgcj v 3.4.0 ave a strange
# issue that make them impossible to popen within zope. # issue that make them impossible to popen within zope.
...@@ -55,459 +55,460 @@ except ImportError: ...@@ -55,459 +55,460 @@ except ImportError:
PDFTK_EXECUTABLE = "pdftk-emulation" PDFTK_EXECUTABLE = "pdftk-emulation"
class PDFTk : class PDFTk :
""" """
A class to wrapp calls to pdftk executable, found at A class to wrapp calls to pdftk executable, found at
http://www.accesspdf.com/pdftk/ http://www.accesspdf.com/pdftk/
""" """
def catPages(self, pdfFile, cat_option) : def catPages(self, pdfFile, cat_option) :
""" limit to a specific range of pages, like pdftk's cat option""" """ limit to a specific range of pages, like pdftk's cat option"""
return self._getOutput( return self._getOutput(
PDFTK_EXECUTABLE+ PDFTK_EXECUTABLE+
" - cat %s output - "%cat_option, pdfFile) " - cat %s output - "%cat_option, pdfFile)
def dumpDataFields(self, pdfFile) : def dumpDataFields(self, pdfFile) :
""" returns the output of pdftk dump_data_fields as dict """ """ returns the output of pdftk dump_data_fields as dict """
return self._parseDumpDataFields(self.dumpDataFieldsTxt(pdfFile)) return self._parseDumpDataFields(self.dumpDataFieldsTxt(pdfFile))
def fillFormWithDict(self, pdfFile, values) : def fillFormWithDict(self, pdfFile, values) :
""" fill the form with values in """ """ fill the form with values in """
return self.fillFormWithFDF(pdfFile, self._createFdf(values)) return self.fillFormWithFDF(pdfFile, self._createFdf(values))
def fillFormWithFDF(self, pdfFile, fdfFile) : def fillFormWithFDF(self, pdfFile, fdfFile) :
""" fill the form of pdfFile with the FDF data fdfFile """ """ fill the form of pdfFile with the FDF data fdfFile """
pdfFormFileName = mktemp(suffix=".pdf") pdfFormFileName = mktemp(suffix=".pdf")
fdfFormFileName = mktemp(suffix=".fdf") fdfFormFileName = mktemp(suffix=".fdf")
if hasattr(pdfFile, "read") : if hasattr(pdfFile, "read") :
pdfFile = pdfFile.read() pdfFile = pdfFile.read()
tmpPdfFile=open(pdfFormFileName, "w") tmpPdfFile = open(pdfFormFileName, "w")
tmpPdfFile.write(pdfFile) tmpPdfFile.write(pdfFile)
tmpPdfFile.close() tmpPdfFile.close()
if hasattr(fdfFile, "read") : if hasattr(fdfFile, "read") :
fdfFile = fdfFile.read() fdfFile = fdfFile.read()
tmpFdfFile=open(fdfFormFileName, "w") tmpFdfFile = open(fdfFormFileName, "w")
tmpFdfFile.write(fdfFile) tmpFdfFile.write(fdfFile)
tmpFdfFile.close() tmpFdfFile.close()
out = self._getOutput( out = self._getOutput(
PDFTK_EXECUTABLE+ PDFTK_EXECUTABLE+
" %s fill_form %s output - "%( " %s fill_form %s output - "%(
pdfFormFileName, fdfFormFileName)) pdfFormFileName, fdfFormFileName))
os.remove(fdfFormFileName) os.remove(fdfFormFileName)
os.remove(pdfFormFileName) os.remove(pdfFormFileName)
return out return out
def dumpDataFieldsTxt(self, pdfFile) : def dumpDataFieldsTxt(self, pdfFile) :
""" returns the output of pdftk dump_data_fields as text, """ returns the output of pdftk dump_data_fields as text,
pdf file is either the file object or its content""" pdf file is either the file object or its content"""
return self._getOutput( return self._getOutput(
PDFTK_EXECUTABLE+" - dump_data_fields", pdfFile, PDFTK_EXECUTABLE+" - dump_data_fields", pdfFile,
assert_not_empty=0) assert_not_empty=0)
def _parseDumpDataFields(self, data_fields_dump) : def _parseDumpDataFields(self, data_fields_dump) :
""" parses the output of pdftk X.pdf dump_data_fields and """ parses the output of pdftk X.pdf dump_data_fields and
returns a sequence of dicts [{key = value}] """ returns a sequence of dicts [{key = value}] """
fields = [] fields = []
for txtfield in data_fields_dump.split("---") : for txtfield in data_fields_dump.split("---") :
field = {} field = {}
for line in txtfield.splitlines() : for line in txtfield.splitlines() :
if line.strip() == "" : if line.strip() == "" :
continue continue
splits = line.split(":", 1) splits = line.split(":", 1)
if len(splits) == 2 : if len(splits) == 2 :
field[splits[0]] = splits[1].strip() field[splits[0]] = splits[1].strip()
if field != {} : if field != {} :
fields += [field] fields += [field]
return fields return fields
def _getOutput(self, command, input=None, assert_not_empty=1) : def _getOutput(self, command, input=None, assert_not_empty=1) :
""" returns the output of command with sending input through command's """ returns the output of command with sending input through command's
input stream (if input parameter is given) """ input stream (if input parameter is given) """
stdout, stdin = popen2.popen2(command) stdout, stdin = popen2.popen2(command)
if input: if input:
if hasattr(input, "read") : if hasattr(input, "read") :
input = input.read() input = input.read()
try : try :
stdin.write(input) stdin.write(input)
except IOError, e: except IOError, e:
raise IOError, str(e) + " ( make sure "\ raise IOError, str(e) + " ( make sure "\
"%s exists and is in your $PATH )"%PDFTK_EXECUTABLE "%s exists and is in your $PATH )"%PDFTK_EXECUTABLE
stdin.close() stdin.close()
ret = stdout.read() ret = stdout.read()
stdout.close() stdout.close()
if assert_not_empty and len(ret) == 0 : if assert_not_empty and len(ret) == 0 :
raise IOError, "Got no output from external program, make sure"\ raise IOError, "Got no output from external program, make sure"\
" %s exists and is in your $PATH"%PDFTK_EXECUTABLE " %s exists and is in your $PATH"%PDFTK_EXECUTABLE
return ret return ret
def _escapeString(self, value) : def _escapeString(self, value) :
if value is None : if value is None :
return "" return ""
string = str(value) string = str(value)
escaped = '' escaped = ''
for c in string : for c in string :
if (ord(c) == 0x28 or # open paren if (ord(c) == 0x28 or # open paren
ord(c) == 0x29 or # close paren ord(c) == 0x29 or # close paren
ord(c) == 0x5c): # backslash ord(c) == 0x5c): # backslash
escaped += '\\' + c escaped += '\\' + c
elif ord(c) < 32 or 126 < ord(c): elif ord(c) < 32 or 126 < ord(c):
escaped += "\\%03o" % ord(c) escaped += "\\%03o" % ord(c)
else: else:
escaped += c escaped += c
return escaped return escaped
def _createFdf(self, values, pdfFormUrl=None) : def _createFdf(self, values, pdfFormUrl=None) :
""" create an fdf document with the dict values """ """ create an fdf document with the dict values """
fdf = "%FDF-1.2\x0d%\xe2\xe3\xcf\xd3\x0d\x0a" fdf = "%FDF-1.2\x0d%\xe2\xe3\xcf\xd3\x0d\x0a"
fdf += "1 0 obj\x0d<< \x0d/FDF << /Fields [ " fdf += "1 0 obj\x0d<< \x0d/FDF << /Fields [ "
for key, value in values.items(): for key, value in values.items():
fdf += "<< /T (%s) /V (%s)>> \x0d"%( fdf += "<< /T (%s) /V (%s)>> \x0d" % (
self._escapeString(key), self._escapeString(key),
self._escapeString(value)) self._escapeString(value))
fdf += "] \x0d" fdf += "] \x0d"
# the PDF form filename or URL, if any # the PDF form filename or URL, if any
if pdfFormUrl not in ("", None) : if pdfFormUrl not in ("", None) :
fdf += "/F ("+self._escapeString(pdfFormUrl)+") \x0d" fdf += "/F ("+self._escapeString(pdfFormUrl)+") \x0d"
fdf += ">> \x0d>> \x0dendobj\x0d"; fdf += ">> \x0d>> \x0dendobj\x0d";
fdf += "trailer\x0d<<\x0d/Root 1 0 R \x0d\x0d>>\x0d%%EOF\x0d\x0a" fdf += "trailer\x0d<<\x0d/Root 1 0 R \x0d\x0d>>\x0d%%EOF\x0d\x0a"
return fdf return fdf
# Constructors # Constructors
manage_addPDFForm = DTMLFile("dtml/PDFForm_add", globals()) manage_addPDFForm = DTMLFile("dtml/PDFForm_add", globals())
def addPDFForm(self, id, title="", pdf_file=None, REQUEST=None): def addPDFForm(self, id, title="", pdf_file=None, REQUEST=None):
""" Add a pdf form to folder. """ """ Add a pdf form to folder. """
# add actual object # add actual object
id = self._setObject(id, PDFForm(id, title, pdf_file)) id = self._setObject(id, PDFForm(id, title, pdf_file))
# upload content # upload content
if pdf_file: if pdf_file:
self._getOb(id).manage_upload(pdf_file) self._getOb(id).manage_upload(pdf_file)
self._getOb(id).content_type="application/pdf" self._getOb(id).content_type="application/pdf"
if REQUEST : if REQUEST :
u = REQUEST['URL1'] u = REQUEST['URL1']
if REQUEST['submit'] == " Add and Edit ": if REQUEST['submit'] == " Add and Edit ":
u = "%s/%s" % (u, quote(id)) u = "%s/%s" % (u, quote(id))
REQUEST.RESPONSE.redirect(u+'/manage_main') REQUEST.RESPONSE.redirect(u+'/manage_main')
class CalculatedValues : class CalculatedValues :
""" """
This class holds a reference to calculated values, for use in TALES, This class holds a reference to calculated values, for use in TALES,
because in PDF Form filling, there is lots of references to others cell because in PDF Form filling, there is lots of references to others cell
values (sums ...). This class will be in TALES context under the key 'cell' values (sums ...). This class will be in TALES context under the key 'cell'
It will make possible the use of TALES expressions like : It will make possible the use of TALES expressions like :
cell/a95 cell/a95
python: cell['a1'] + cell['a2'] python: cell['a1'] + cell['a2']
""" """
security = ClassSecurityInfo() security = ClassSecurityInfo()
def __init__(self, values, key, not_founds) : def __init__(self, values, key, not_founds) :
""" 'values' are a dict of already calculated values """ 'values' are a dict of already calculated values
'key' is the key we are evaluating 'key' is the key we are evaluating
'not_founds' is the list in which we will put not found values """ 'not_founds' is the list in which we will put not found values """
self.__values = values self.__values = values
self.__key = key self.__key = key
self.__not_founds = not_founds self.__not_founds = not_founds
def __getitem__(self, attr) : def __getitem__(self, attr) :
if not self.__values.has_key(attr) : if not self.__values.has_key(attr) :
self.__not_founds.append(attr) self.__not_founds.append(attr)
return 0 # We do not return None, so that cell['a1'] + cell['a2'] return 0 # We do not return None, so that cell['a1'] + cell['a2']
# doesn't complain that NoneType doesn't support + when a1 not found # doesn't complain that NoneType doesn't support + when a1 not found
return self.__values[attr] return self.__values[attr]
__getattr__ = __getitem__ __getattr__ = __getitem__
allow_class(CalculatedValues) allow_class(CalculatedValues)
class PDFForm(File): class PDFForm(File):
"""
This class allows to fill PDF Form with TALES expressions,
using a TALES expression for each cell.
"""
meta_type = "ERP5 PDF Form"
icon = "www/PDFForm.png"
# Declarative Security
security = ClassSecurityInfo()
# Declarative properties
property_sheets = ( PropertySheet.Base
, PropertySheet.SimpleItem
)
# Constructors
constructors = (manage_addPDFForm, addPDFForm)
manage_options = ( (
{'label':'Edit Cell TALES', 'action':'manage_cells'},
{'label':'Display Cell Names', 'action':'showCellNames'},
{'label':'Test PDF generation', 'action':'generatePDF'},
{'label':'View original', 'action':'viewOriginal'},
) +
filter(lambda option:option['label'] != "View", File.manage_options)
)
pdftk = PDFTk()
def __init__ (self, id, title, pdf_file) :
# holds all the cell informations, even those not related to this form
self.all_cells = PersistentMapping()
# holds the cells related to this pdf form
self.cells = PersistentMapping()
# the page range we want to print
self.__page_range__ = ""
# the method to format values
self.__format_method__ = ""
if not pdf_file :
raise ValueError ("The pdf form file should not be empty")
# File constructor will call manage_upload, so we don't need to call it
File.__init__(self, id, title, pdf_file)
security.declareProtected('Change Images and Files', 'manage_upload')
def manage_upload(self, file=None, REQUEST=None) :
""" Zope calls this when the content of the enclosed file changes.
The 'cells' attribute is updated, but already defined cells are not
erased, they are saved in the 'all_cells' attribute so if the pdf
file is reverted, you do not loose the cells definitions.
""" """
This class allows to fill PDF Form with TALES expressions, if not file or not hasattr(file, "read") :
using a TALES expression for each cell. raise ValueError ("The pdf form file should not be empty")
file.seek(0) # file is always valid here
values = self.pdftk.dumpDataFields(file)
for v in values :
if v["FieldType"] != "Button" :
k = v["FieldName"]
if not self.all_cells.has_key(k) :
self.cells[k] = ""
else :
self.cells[k] = self.all_cells[k]
self.all_cells.update(self.cells)
file.seek(0)
File.manage_upload(self, file, REQUEST)
if REQUEST:
message = "Saved changes."
return self.manage_main(self, REQUEST, manage_tabs_message=message)
security.declareProtected('View management screens', 'manage_cells')
manage_cells = PageTemplateFile('www/PDFForm_manageCells',
globals(), __name__='manage_cells')
security.declareProtected('View', 'manage_FTPget')
def manage_FTPget(self, REQUEST, RESPONSE) :
""" get this pdf form via webDAV/FTP, it returns an XML
representation of all the fields, then the pdf itself."""
from xml.dom.minidom import getDOMImplementation
impl = getDOMImplementation()
newdoc = impl.createDocument(None, "pdfform", None)
top_element = newdoc.documentElement
cells = newdoc.createElement('cells')
for cell in self.cells.keys() :
cell_node = newdoc.createElement('cell')
cell_node.setAttribute('name', cell)
tales = newdoc.createTextNode(self.cells[cell])
cell_node.appendChild(tales)
cells.appendChild(cell_node)
top_element.appendChild(cells)
pdf = newdoc.createTextNode(str(self.data))
top_element.appendChild(pdf)
content = newdoc.toprettyxml()
RESPONSE.setHeader('Content-Type', 'application/x-erp5-pdfform')
RESPONSE.setHeader('Content-Length', len(content))
RESPONSE.write(content)
manage_DAVget = manage_FTPget
def PUT(self, REQUEST, RESPONSE):
"""(does not) Handle HTTP PUT requests."""
RESPONSE.setStatus(501)
return RESPONSE
manage_FTPput = PUT
security.declareProtected('View', 'viewOriginal')
def viewOriginal(self, REQUEST=None, RESPONSE=None, *args, **kwargs) :
""" publish original pdf """
pdf = File.index_html(self, REQUEST, RESPONSE, *args, **kwargs)
RESPONSE.setHeader('Content-Type', 'application/pdf')
RESPONSE.setHeader('Content-Disposition', 'inline;filename="%s.pdf"'
% (self.title_or_id()))
return pdf
security.declareProtected('View', 'showCellNames')
def showCellNames(self, REQUEST=None, RESPONSE=None, *args, **kwargs) :
""" generates a pdf with fields filled-in by their names,
usefull to fill in settings.
""" """
meta_type = "ERP5 PDF Form" values = {}
icon = "www/PDFForm.png" for cell in self.cells.keys() :
values[cell] = cell
# Declarative Security pdf = self.pdftk.fillFormWithDict(str(self.data), values)
security = ClassSecurityInfo() if RESPONSE :
RESPONSE.setHeader('Content-Type', 'application/pdf')
# Declarative properties RESPONSE.setHeader('Content-Length', len(pdf))
property_sheets = ( PropertySheet.Base RESPONSE.setHeader('Content-Disposition',
, PropertySheet.SimpleItem 'inline;filename="%s.template.pdf"' % (
) self.title_or_id()))
return pdf
# Constructors
constructors = (manage_addPDFForm, addPDFForm) security.declareProtected('Change Images and Files', 'doEditCells')
def doEditCells(self, REQUEST):
manage_options = ( """ This is the action to the 'Edit Cell TALES' tab. """
( if SUPPORTS_WEBDAV_LOCKS and self.wl_isLocked():
{'label':'Edit Cell TALES', 'action':'manage_cells'}, raise ResourceLockedError, "File is locked via WebDAV"
{'label':'Display Cell Names', 'action':'showCellNames'},
{'label':'Test PDF generation', 'action':'generatePDF'}, for k, v in self.cells.items() :
{'label':'View original', 'action':'viewOriginal'}, self.setCellTALES(k, REQUEST.get(str(k), v))
) + self.__format_method__ = REQUEST.get("__format_method__")
filter(lambda option:option['label'] != "View", File.manage_options) self.__page_range__ = REQUEST.get("__page_range__")
)
message = "Saved changes."
pdftk = PDFTk() if getattr(self, '_v_warnings', None):
message = ("<strong>Warning:</strong> <i>%s</i>"
def __init__ (self, id, title, pdf_file) : % '<br>'.join(self._v_warnings))
# holds all the cell informations, even those not related to this form return self.manage_cells(manage_tabs_message=message)
self.all_cells = PersistentMapping()
# holds the cells related to this pdf form security.declareProtected('View', 'generatePDF')
self.cells = PersistentMapping() def generatePDF(self, REQUEST=None, RESPONSE=None, *args, **kwargs) :
# the page range we want to print """ generates the PDF with form filled in """
self.__page_range__ = "" values = self.calculateCellValues(REQUEST, *args, **kwargs)
# the method to format values context = {'here' : self.aq_parent, 'request' : REQUEST}
self.__format_method__ = "" if hasattr(self, "__format_method__") \
and self.__format_method__ not in ('', None) :
if not pdf_file : compiled_tales = getEngine().compile(self.__format_method__)
raise ValueError ("The pdf form file should not be empty") format_method = getEngine().getContext(context).evaluate(compiled_tales)
# File constructor will call manage_upload, so we don't need to call it # try to support both method name and method object
File.__init__(self, id, title, pdf_file) if not callable(format_method) :
format_method = self.restrictedTraverse(format_method)
security.declareProtected('Change Images and Files', 'manage_upload') if callable(format_method) :
def manage_upload(self, file=None, REQUEST=None) : for k, v in values.items() :
""" Zope calls this when the content of the enclosed file changes. values[k] = format_method(v, cell_name=k)
The 'cells' attribute is updated, but already defined cells are not else :
erased, they are saved in the 'all_cells' attribute so if the pdf LOG("PDFForm", 0, 'format method (%r) is not callable' % format_method)
file is reverted, you do not loose the cells definitions. data = str(self.data)
""" if self.__page_range__ not in ('', None) :
if not file or not hasattr(file, "read") : compiled_tales = getEngine().compile(self.__page_range__)
raise ValueError ("The pdf form file should not be empty") page_range = getEngine().getContext(context).evaluate(compiled_tales)
if page_range :
file.seek(0) # file is always valid here data = self.pdftk.catPages(str(self.data), page_range)
values = self.pdftk.dumpDataFields(file) pdf = self.pdftk.fillFormWithDict(data, values)
for v in values : if RESPONSE :
if v["FieldType"] != "Button" : RESPONSE.setHeader('Content-Type', 'application/pdf')
k = v["FieldName"] RESPONSE.setHeader('Content-Length', len(pdf))
if not self.all_cells.has_key(k) : RESPONSE.setHeader('Content-Disposition', 'inline;filename="%s.pdf"'
self.cells[k] = ""
else :
self.cells[k] = self.all_cells[k]
self.all_cells.update(self.cells)
file.seek(0)
File.manage_upload(self, file, REQUEST)
if REQUEST:
message="Saved changes."
return self.manage_main(self, REQUEST, manage_tabs_message=message)
security.declareProtected('View management screens', 'manage_cells')
manage_cells = PageTemplateFile('www/PDFForm_manageCells',
globals(), __name__='manage_cells')
security.declareProtected('View', 'manage_FTPget')
def manage_FTPget(self, REQUEST, RESPONSE) :
""" get this pdf form via webDAV/FTP, it returns an XML
representation of all the fields, then the pdf itself."""
from xml.dom.minidom import getDOMImplementation
impl = getDOMImplementation()
newdoc = impl.createDocument(None, "pdfform", None)
top_element = newdoc.documentElement
cells = newdoc.createElement('cells')
for cell in self.cells.keys() :
cell_node = newdoc.createElement('cell')
cell_node.setAttribute('name', cell)
tales = newdoc.createTextNode(self.cells[cell])
cell_node.appendChild(tales)
cells.appendChild(cell_node)
top_element.appendChild(cells)
pdf = newdoc.createTextNode(str(self.data))
top_element.appendChild(pdf)
content = newdoc.toprettyxml()
RESPONSE.setHeader('Content-Type', 'application/x-erp5-pdfform')
RESPONSE.setHeader('Content-Length', len(content))
RESPONSE.write(content)
manage_DAVget = manage_FTPget
def PUT(self, REQUEST, RESPONSE):
"""(does not) Handle HTTP PUT requests."""
RESPONSE.setStatus(501)
return RESPONSE
manage_FTPput = PUT
security.declareProtected('View', 'viewOriginal')
def viewOriginal(self, REQUEST=None, RESPONSE=None, *args, **kwargs) :
""" publish original pdf """
pdf = File.index_html(self, REQUEST, RESPONSE, *args, **kwargs)
RESPONSE.setHeader('Content-Type', 'application/pdf')
RESPONSE.setHeader('Content-Disposition', 'inline;filename="%s.pdf"'
% (self.title_or_id())) % (self.title_or_id()))
return pdf return pdf
index_html = generatePDF
security.declareProtected('View', 'showCellNames') __call__ = generatePDF
def showCellNames(self, REQUEST=None, RESPONSE=None, *args, **kwargs) :
""" generates a pdf with fields filled-in by their names, security.declareProtected('View', 'calculateCellValues')
usefull to fill in settings. def calculateCellValues(self, REQUEST=None, *args, **kwargs) :
""" """ returns a dict of cell values """
values = {} # values to be returned
for cell in self.cells.keys() : values = {}
values[cell] = cell # list of values that need to be reevaluated (i.e. they depend on the
pdf = self.pdftk.fillFormWithDict(str(self.data), values) # value of a cell that was not already evaluated when evaluating them )
if RESPONSE : uncalculated_values = []
RESPONSE.setHeader('Content-Type', 'application/pdf') for cell_name in self.cells.keys() :
RESPONSE.setHeader('Content-Length', len(pdf)) not_founds = []
RESPONSE.setHeader('Content-Disposition', value = self.evaluateCell(cell_name, REQUEST = REQUEST,
'inline;filename="%s.template.pdf"'%( cell = SafeMapping(CalculatedValues(
self.title_or_id())) values, cell_name, not_founds)))
return pdf if len(not_founds) != 0 :
uncalculated_values.append(cell_name)
security.declareProtected('Change Images and Files', 'doEditCells') else :
def doEditCells(self, REQUEST): values[cell_name] = value
""" This is the action to the 'Edit Cell TALES' tab. """ # now we iterate on the list of uncalculated values, trying
if SUPPORTS_WEBDAV_LOCKS and self.wl_isLocked(): # to evaluate them again, if an iteration doesn't decrement
raise ResourceLockedError, "File is locked via WebDAV" # the length of this list, there are some circular references
# and we cannot continue.
for k, v in self.cells.items() : while 1 :
self.setCellTALES(k, REQUEST.get(str(k), v)) uncalculated_values_len = len(uncalculated_values)
self.__format_method__ = REQUEST.get("__format_method__") if uncalculated_values_len == 0 :
self.__page_range__ = REQUEST.get("__page_range__") return values
for cell_name in uncalculated_values :
message = "Saved changes." not_founds = []
if getattr(self, '_v_warnings', None): value = self.evaluateCell(cell_name, REQUEST = REQUEST,
message = ("<strong>Warning:</strong> <i>%s</i>" cell = SafeMapping(CalculatedValues(
% '<br>'.join(self._v_warnings)) values, cell_name, not_founds)))
return self.manage_cells(manage_tabs_message=message) if len(not_founds) == 0 :
uncalculated_values.remove(cell_name)
security.declareProtected('View', 'generatePDF') values[cell_name] = value
def generatePDF(self, REQUEST=None, RESPONSE=None, *args, **kwargs) : if len(uncalculated_values) == uncalculated_values_len :
""" generates the PDF with form filled in """ raise ValueError, "Circular reference: unable to evaluate cells " \
values = self.calculateCellValues(REQUEST, *args, **kwargs) + `uncalculated_values`
context = {'here' : self.aq_parent, 'request' : REQUEST}
if hasattr(self, "__format_method__") and self.__format_method__ not in ('', None) : security.declareProtected('View', 'getCellNames')
compiled_tales = getEngine().compile(self.__format_method__) def getCellNames(self, REQUEST=None) :
format_method = getEngine().getContext(context).evaluate(compiled_tales) """ returns a list of cell names """
# try to support both method name and method object names = self.cells.keys()
if not callable(format_method) : names.sort()
format_method = self.restrictedTraverse(format_method) return names
if callable(format_method) :
for k, v in values.items() : security.declareProtected('Change Images and Files', 'setCellTALES')
values[k] = format_method(v, cell_name=k) def setCellTALES(self, cell_name, TALES):
else : """ changes the TALES expression that will be used to evaluate
LOG("PDFForm", 0, 'format method ("%r") is not callable' % format_method) cell value """
data = str(self.data) if type(TALES) != types.StringType :
if self.__page_range__ not in ('', None) : LOG("PDFForm", 100,
compiled_tales = getEngine().compile(self.__page_range__) 'TALES is not a string for cell "%s", it is = "%s"'
page_range = getEngine().getContext(context).evaluate(compiled_tales) %(cell_name, `TALES`))
if page_range : raise ValueError, 'TALES must be a string'
data = self.pdftk.catPages(str(self.data), page_range) self.all_cells[str(cell_name)] = self.cells[str(cell_name)] = TALES
pdf = self.pdftk.fillFormWithDict(data, values)
if RESPONSE : security.declareProtected('View', 'getCellTALES')
RESPONSE.setHeader('Content-Type', 'application/pdf') def getCellTALES(self, cell_name):
RESPONSE.setHeader('Content-Length', len(pdf)) """ returns the TALES expression associated with this cell """
RESPONSE.setHeader('Content-Disposition', 'inline;filename="%s.pdf"' return self.cells[str(cell_name)]
% (self.title_or_id()))
return pdf security.declareProtected('View', 'evaluateCell')
index_html = generatePDF def evaluateCell(self, cell_name, REQUEST=None, **kwargs):
__call__ = generatePDF """ evaluate the TALES expression for this cell """
cell_name = str(cell_name)
security.declareProtected('View', 'calculateCellValues') # we don't pass empty strings in TALES engine
def calculateCellValues(self, REQUEST=None, *args, **kwargs) : # (and this also raises the KeyError for non existant cells)
""" returns a dict of cell values """ if not self.cells[cell_name] :
# values to be returned return None
values = {} context = {'here' : self.aq_parent, 'request' : REQUEST}
# list of values that need to be reevaluated (i.e. they depend on the context.update (kwargs)
# value of a cell that was not already evaluated when evaluating them )
uncalculated_values = [] compiled_tales = getEngine().compile(self.cells[cell_name])
for cell_name in self.cells.keys() : value = getEngine().getContext(context).evaluate(compiled_tales)
not_founds = [] return value
value = self.evaluateCell(cell_name, REQUEST = REQUEST,
cell = SafeMapping(CalculatedValues( security.declareProtected('Change Images and Files', 'setAllCellTALES')
values, cell_name, not_founds))) def setAllCellTALES(self, new_cells) :
if len(not_founds) != 0 : """ set all cell values from a dict containing { name: TALES } """
uncalculated_values.append(cell_name) for cell_name, cell_TALES in new_cells.items() :
else : self.setCellTALES(cell_name, cell_TALES)
values[cell_name] = value
# now we iterate on the list of uncalculated values, trying security.declareProtected('View', 'getFormatMethodTALES')
# to evaluate them again, if an iteration doesn't decrement def getFormatMethodTALES(self):
# the length of this list, there are some circular references """ returns the TALES expression for the format method attribute """
# and we cannot continue. # backward compat
while 1 : if not hasattr(self, "__format_method__") :
uncalculated_values_len = len(uncalculated_values) self.__format_method__ = ""
if uncalculated_values_len == 0 : return self.__format_method__
return values
for cell_name in uncalculated_values : security.declareProtected('Change Images and Files', 'setFormatMethodTALES')
not_founds = [] def setFormatMethodTALES(self, TALES):
value = self.evaluateCell(cell_name, REQUEST = REQUEST, """ sets TALES expression for the format method attribute """
cell = SafeMapping(CalculatedValues( self.__format_method__ = str(TALES)
values, cell_name, not_founds)))
if len(not_founds) == 0 : security.declareProtected('View', 'getPageRangeTALES')
uncalculated_values.remove(cell_name) def getPageRangeTALES(self):
values[cell_name] = value """ returns the TALES expression for the page range attribute """
if len(uncalculated_values) == uncalculated_values_len : return self.__page_range__
raise "Circular reference", "unable to evaluate cells " \
+ `uncalculated_values` security.declareProtected('Change Images and Files', 'setPageRangeTALES')
def setPageRangeTALES(self, TALES):
security.declareProtected('View', 'getCellNames') """ sets TALES expression for the page range attribute """
def getCellNames(self, REQUEST=None) : self.__page_range__ = str(TALES)
""" returns a list of cell names """
names = self.cells.keys()
names.sort()
return names
security.declareProtected('Change Images and Files', 'setCellTALES')
def setCellTALES(self, cell_name, TALES):
""" changes the TALES expression that will be used to evaluate
cell value """
if type(TALES) != types.StringType :
LOG("PDFForm", 100,
'TALES is not a string for cell "%s", it is = "%s"'
%(cell_name, `TALES`))
raise ValueError, 'TALES must be a string'
self.all_cells[str(cell_name)] = self.cells[str(cell_name)] = TALES
security.declareProtected('View', 'getCellTALES')
def getCellTALES(self, cell_name):
""" returns the TALES expression associated with this cell """
return self.cells[str(cell_name)]
security.declareProtected('View', 'evaluateCell')
def evaluateCell(self, cell_name, REQUEST=None, **kwargs):
""" evaluate the TALES expression for this cell """
cell_name = str(cell_name)
# we don't pass empty strings in TALES engine
# (and this also raises the KeyError for non existant cells)
if not self.cells[cell_name] :
return None
context = {'here' : self.aq_parent, 'request' : REQUEST}
context.update (kwargs)
compiled_tales = getEngine().compile(self.cells[cell_name])
value = getEngine().getContext(context).evaluate(compiled_tales)
return value
security.declareProtected('Change Images and Files', 'setAllCellTALES')
def setAllCellTALES(self, new_cells) :
""" set all cell values from a dict containing { name: TALES } """
for cell_name, cell_TALES in new_cells.items() :
self.setCellTALES(cell_name, cell_TALES)
security.declareProtected('View', 'getFormatMethodTALES')
def getFormatMethodTALES(self):
""" returns the TALES expression for the format method attribute """
# backward compat
if not hasattr(self, "__format_method__") :
self.__format_method__ = ""
return self.__format_method__
security.declareProtected('Change Images and Files', 'setFormatMethodTALES')
def setFormatMethodTALES(self, TALES):
""" sets TALES expression for the format method attribute """
self.__format_method__ = str(TALES)
security.declareProtected('View', 'getPageRangeTALES')
def getPageRangeTALES(self):
""" returns the TALES expression for the page range attribute """
return self.__page_range__
security.declareProtected('Change Images and Files', 'setPageRangeTALES')
def setPageRangeTALES(self, TALES):
""" sets TALES expression for the page range attribute """
self.__page_range__ = str(TALES)
InitializeClass(PDFForm) InitializeClass(PDFForm)
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment