PDFDocument.py 10 KB
Newer Older
1
# -*- coding: utf-8 -*-
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
##############################################################################
#
# Copyright (c) 2002-2006 Nexedi SARL and Contributors. All Rights Reserved.
#
# 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.
#
##############################################################################

29 30
import tempfile, os, cStringIO

31
from AccessControl import ClassSecurityInfo
32 33
from Products.CMFCore.utils import getToolByName, _setCacheHeaders,\
    _ViewEmulator
34

35
from Products.ERP5Type import Permissions, PropertySheet, Constraint, interfaces
36 37
from Products.ERP5Type.Cache import CachingMethod
from Products.ERP5.Document.Image import Image
38 39
from Products.ERP5.Document.Document import ConversionError
from Products.ERP5.mixin.cached_convertable import CachedConvertableMixin
40

41
from zLOG import LOG, WARNING
42

43
class PDFDocument(Image, CachedConvertableMixin):
44
  """
45 46 47
  PDFDocument is a subclass of Image which is able to
  extract text content from a PDF file either as text
  or as HTML.
48 49
  """
  # CMF Type Definition
50
  meta_type = 'ERP5 PDF Document'
51 52 53 54 55 56 57 58
  portal_type = 'PDF'

  # Declarative security
  security = ClassSecurityInfo()
  security.declareObjectProtected(Permissions.AccessContentsInformation)

  # Default Properties
  property_sheets = ( PropertySheet.Base
59
                    , PropertySheet.XMLObject
60 61 62 63 64 65
                    , PropertySheet.CategoryCore
                    , PropertySheet.DublinCore
                    , PropertySheet.Version
                    , PropertySheet.Reference
                    , PropertySheet.Document
                    , PropertySheet.Data
66 67 68
                    , PropertySheet.ExternalDocument
                    , PropertySheet.Url
                    , PropertySheet.Periodicity
69 70
                    )

71 72 73 74
  searchable_property_list = ('asText', 'title', 'description', 'id', 'reference',
                              'version', 'short_title',
                              'subject', 'source_reference', 'source_project_title',)

75
  security.declareProtected(Permissions.View, 'index_html')
76 77
  def index_html(self, REQUEST, RESPONSE, display=None, format='', quality=75, 
                                          resolution=None, frame=0):
78
    """
79 80 81
      Returns data in the appropriate format (graphical)
      it is always a zip because multi-page pdfs are converted into a zip
      file of many images
82
    """
83 84 85 86 87 88 89 90
    _setCacheHeaders(_ViewEmulator().__of__(self), {'format' : format})
    if format is '':
      if self.getSourceReference() is not None:
        filename = self.getSourceReference()
      else:
        filename = self.getId()
      RESPONSE.setHeader('Content-Disposition',
                         'attachment; filename="%s"' % filename)
91
      RESPONSE.setHeader('Content-Type', 'application/pdf')
92
      return str(self.data)
93 94 95 96 97 98 99
    if format in ('html', 'txt', 'text'):
      mime, data = self.convert(format)
      RESPONSE.setHeader('Content-Length', len(data))
      RESPONSE.setHeader('Content-Type', '%s;charset=UTF-8' % mime)
      RESPONSE.setHeader('Accept-Ranges', 'bytes')
      return data
    return Image.index_html(self, REQUEST, RESPONSE, display=display,
100 101
                            format=format, quality=quality,
                            resolution=resolution, frame=frame)
102 103 104 105 106 107 108

  # Conversion API
  security.declareProtected(Permissions.ModifyPortalContent, 'convert')
  def convert(self, format, **kw):
    """
    Implementation of conversion for PDF files
    """
109
    if format == 'html':
110 111 112
      try:
        return self.getConversion(format=format)
      except KeyError:
113
        mime = 'text/html'
114
        data = self._convertToHTML()
115 116
        self.setConversion(data, mime=mime, format=format)
        return (mime, data)
117
    elif format in ('txt', 'text'):
118 119 120
      try:
        return self.getConversion(format='txt')
      except KeyError:
121
        mime = 'text/plain'
122
        data = self._convertToText()
123 124
        self.setConversion(data, mime=mime, format='txt')
        return (mime, data)
125 126 127 128 129
    else:
      return Image.convert(self, format, **kw)

  security.declareProtected(Permissions.ModifyPortalContent, 'populateContent')
  def populateContent(self):
130
    """
131 132 133
      Convert each page to an Image and populate the
      PDF directory with converted images. May be useful
      to provide online PDF reader
134
    """
135
    raise NotImplementedError
136 137

  security.declarePrivate('_convertToText')
138
  def _convertToText(self):
139
    """
140
      Convert the PDF text content to text with pdftotext
141
    """
142 143
    if not self.data:
      return ''
144
    tmp = tempfile.NamedTemporaryFile()
145
    tmp.write(str(self.data))
146 147 148 149 150 151
    tmp.seek(0)
    cmd = 'pdftotext -layout -enc UTF-8 -nopgbrk %s -' % tmp.name
    r = os.popen(cmd)
    h = r.read()
    tmp.close()
    r.close()
152 153 154 155 156 157 158 159 160 161 162 163
    
    if h != '':
      return h
    else:
      # Try to use OCR
      # As high dpi images are required, it may take some times to convert the
      # pdf. 
      # It may be required to use activities to fill the cache and at the end, 
      # to calculate the final result
      text = ''
      content_information = self.getContentInformation()
      page_count = int(content_information.get('Pages', 0))
164 165 166 167 168 169 170 171 172 173 174 175 176 177 178
      try:
        # if the dimension is too big, rasterized image can be too
        # big. so we limit the maximum of rasterized image to 4096
        # pixles.
        # XXX since the dimention can be different on each page, it is
        # better to call 'pdfinfo -f page_num -l page_num' to get the
        # size of each page.
        max_size = 4096
        size = content_information.get('Page size',
                                       '%s x %s pts' % (max_size, max_size))
        width = int(size.split(' ')[0])
        height = int(size.split(' ')[2])
        resolution = 72.0 * max_size / max(width, height)
      except ValueError, ZeroDivisionError:
        resolution = None
179 180
      for page_number in range(page_count):
        src_mimetype, png_data = self.convert(
181
            'png', quality=100, resolution=resolution,
182 183 184 185 186 187 188 189 190 191
            frame=page_number, display='identical')
        if not src_mimetype.endswith('png'):
          continue
        content = '%s' % png_data
        mime_type = getToolByName(self, 'mimetypes_registry').\
                                    lookupExtension('name.%s' % 'txt')
        if content is not None:
          portal_transforms = getToolByName(self, 'portal_transforms')
          result = portal_transforms.convertToData(mime_type, content,
                                                   context=self,
192
                                                   filename=self.getTitleOrId(),
193 194
                                                   mimetype=src_mimetype)
          if result is None:
195 196
            raise ConversionError('PDFDocument conversion error. '
                                  'portal_transforms failed to convert to %s: %r' % (mime_type, self))
197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212
          text += result
      return text

  security.declareProtected('View', 'getSizeFromImageDisplay')
  def getSizeFromImageDisplay(self, image_display):
    """
    Return the size for this image display, or None if this image display name
    is not known. If the preference is not set, (0, 0) is returned.
    """
    # identical parameter can be considered as a hack, in order not to
    # resize the image to prevent text distorsion when using OCR.
    # A cleaner API is required.
    if image_display == 'identical':
      return (self.getWidth(), self.getHeight())
    else:
      return Image.getSizeFromImageDisplay(self, image_display)
213 214 215 216 217

  security.declarePrivate('_convertToHTML')
  def _convertToHTML(self):
    """
    Convert the PDF text content to HTML with pdftohtml
218 219 220

    NOTE: XXX check that command exists and was executed
    successfully
221
    """
222 223
    if not self.data:
      return ''
224
    tmp = tempfile.NamedTemporaryFile()
225
    tmp.write(str(self.data))
226 227 228 229 230 231 232
    tmp.seek(0)
    cmd = 'pdftohtml -enc UTF-8 -stdout -noframes -i %s' % tmp.name
    r = os.popen(cmd)
    h = r.read()
    tmp.close()
    r.close()
    h = h.replace('<BODY bgcolor="#A0A0A0"', '<BODY ') # Quick hack to remove bg color - XXX
233
    h = h.replace('href="%s.html' % tmp.name.split(os.sep)[-1], 'href="asEntireHTML') # Make links relative
234 235 236 237 238 239 240
    return h

  security.declareProtected(Permissions.AccessContentsInformation, 'getContentInformation')
  def getContentInformation(self):
    """
    Returns the information about the PDF document with
    pdfinfo.
241 242 243

    NOTE: XXX check that command exists and was executed
    successfully
244
    """
245 246 247 248
    try:
      return self._content_information.copy()
    except AttributeError:
      pass
249
    tmp = tempfile.NamedTemporaryFile()
250
    tmp.write(str(self.data))
251 252 253 254 255 256 257 258 259 260 261 262
    tmp.seek(0)
    cmd = 'pdfinfo -meta -box %s' % tmp.name
    r = os.popen(cmd)
    h = r.read()
    tmp.close()
    r.close()
    result = {}
    for line in h.splitlines():
      item_list = line.split(':')
      key = item_list[0].strip()
      value = ':'.join(item_list[1:]).strip()
      result[key] = value
263 264 265 266 267 268
    self._content_information = result
    return result.copy()

  def _setFile(self, data, precondition=None):
    try:
      del self._content_information
Yusei Tahara's avatar
Yusei Tahara committed
269
    except (AttributeError, KeyError):
270 271
      pass
    Image._setFile(self, data, precondition)