document.erp5.PDFDocument.py 12.9 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
import tempfile, os, pickle
30

31
import zope.interface
32
from AccessControl import ClassSecurityInfo
33

34 35
from Products.ERP5Type import Permissions, PropertySheet
from erp5.component.interface.IWatermarkable import IWatermarkable
36
from Products.ERP5.Document.Image import Image
37
from Products.ERP5.Document.Document import ConversionError
38
from subprocess import Popen, PIPE
39
from zLOG import LOG, INFO, PROBLEM
Nicolas Dumazet's avatar
Nicolas Dumazet committed
40
import errno
41
from StringIO import StringIO
42

43
class PDFDocument(Image):
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
  zope.interface.implements(IWatermarkable)
72 73 74 75 76 77 78 79 80 81 82 83 84

  security.declareProtected(Permissions.AccessContentsInformation,
                            'getWatermarkedData')
  def getWatermarkedData(self, watermark_data, repeat_watermark=True,
                         watermark_start_page=0, **kw):
    """See interface

    * watermark_data is the PDF data (as a string) to use as a watermark.
    * If repeat_watermark is true, then the watermark will be applied on all
      pages, otherwise it is applied only once.
    * Watermark is applied at all pages starting watermark_start_page (this
      index is 0 based)
    """
Aurel's avatar
Aurel committed
85 86 87 88 89 90 91 92 93 94 95 96
    try:
      from PyPDF2 import PdfFileWriter, PdfFileReader
    except ImportError:
      pass
    else:
      if not watermark_data:
        raise ValueError("watermark_data cannot not be empty")
      if not self.hasData():
        raise ValueError("Cannot watermark an empty document")
      self_reader = PdfFileReader(StringIO(self.getData()))
      watermark_reader = PdfFileReader(StringIO(watermark_data))
      watermark_page_count = watermark_reader.getNumPages()
97

Aurel's avatar
Aurel committed
98
      output = PdfFileWriter()
99

Aurel's avatar
Aurel committed
100 101 102 103 104 105 106 107 108 109 110 111
      for page_number in range(self_reader.getNumPages()):
        self_page = self_reader.getPage(page_number)
        watermark_page = None
        if page_number >= watermark_start_page:
          if repeat_watermark:
            watermark_page = watermark_reader.getPage(
              (page_number - watermark_start_page) % watermark_page_count)
          elif page_number < (watermark_page_count + watermark_start_page):
            watermark_page = watermark_reader.getPage(page_number - watermark_start_page)
          if watermark_page is not None:
            self_page.mergePage(watermark_page)
        output.addPage(self_page)
112

Aurel's avatar
Aurel committed
113 114 115
      outputStream = StringIO()
      output.write(outputStream)
      return outputStream.getvalue()
116

117
  # Conversion API
118
  def _convert(self, format, **kw):
119 120 121
    """
    Implementation of conversion for PDF files
    """
122
    if format == 'html':
123 124 125
      try:
        return self.getConversion(format=format)
      except KeyError:
126
        mime = 'text/html'
127
        data = self._convertToHTML()
128 129
        self.setConversion(data, mime=mime, format=format)
        return (mime, data)
130
    elif format in ('txt', 'text'):
131 132 133
      try:
        return self.getConversion(format='txt')
      except KeyError:
134
        mime = 'text/plain'
135
        data = self._convertToText()
136 137
        self.setConversion(data, mime=mime, format='txt')
        return (mime, data)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
138 139 140 141 142 143 144 145
    elif format in ('djvu', 'DJVU'):
      try:
        return self.getConversion(format='djvu')
      except KeyError:
        mime = 'image/vnd.djvu'
        data = self._convertToDJVU()
        self.setConversion(data, mime=mime, format='djvu')
        return (mime, data)
146 147
    elif format in ('', None,) or format=='pdf':
      # return original content
148
      return self.getContentType(), self.getData()
149
    else:
150 151 152 153 154
      if kw.get('frame', None) is None:
        # when converting to image from PDF we care for first page only
        # this will make sure that only first page is used and not whole content of
        # PDF file read & converted which is a performance issue
        kw['frame'] = 0
155
      return Image._convert(self, format, **kw)
156 157 158

  security.declareProtected(Permissions.ModifyPortalContent, 'populateContent')
  def populateContent(self):
159
    """
160 161 162
      Convert each page to an Image and populate the
      PDF directory with converted images. May be useful
      to provide online PDF reader
163
    """
164
    raise NotImplementedError
165 166

  security.declarePrivate('_convertToText')
167
  def _convertToText(self):
168
    """
169
      Convert the PDF text content to text with pdftotext
170
    """
171
    if not self.hasData():
172
      return ''
Nicolas Delaby's avatar
Nicolas Delaby committed
173 174
    mime_type = 'text/plain'
    portal_transforms = self.getPortalObject().portal_transforms
175
    filename = self.getFilename()
Nicolas Delaby's avatar
Nicolas Delaby committed
176 177 178 179 180
    result = portal_transforms.convertToData(mime_type, str(self.getData()),
                                             context=self, filename=filename,
                                             mimetype=self.getContentType())
    if result:
      return result
181 182 183
    else:
      # Try to use OCR
      # As high dpi images are required, it may take some times to convert the
184 185
      # pdf.
      # It may be required to use activities to fill the cache and at the end,
186 187 188 189 190
      # to calculate the final result
      text = ''
      content_information = self.getContentInformation()
      page_count = int(content_information.get('Pages', 0))
      for page_number in range(page_count):
191
        src_mimetype, png_data = self._convert(
192
            'png', quality=100, resolution=300,
193 194 195
            frame=page_number, display='identical')
        if not src_mimetype.endswith('png'):
          continue
Nicolas Delaby's avatar
Nicolas Delaby committed
196
        content = str(png_data)
197
        if content is not None:
Nicolas Delaby's avatar
Nicolas Delaby committed
198
          filename = self.getStandardFilename(format='png')
199 200
          result = portal_transforms.convertToData(mime_type, content,
                                                   context=self,
Nicolas Delaby's avatar
Nicolas Delaby committed
201
                                                   filename=filename,
202 203
                                                   mimetype=src_mimetype)
          if result is None:
204 205
            raise ConversionError('PDFDocument conversion error. '
                                  'portal_transforms failed to convert to %s: %r' % (mime_type, self))
206 207 208
          text += result
      return text

209
  security.declareProtected(Permissions.AccessContentsInformation, 'getSizeFromImageDisplay')
210 211 212 213 214 215 216 217 218 219 220 221
  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)
222 223 224

  security.declarePrivate('_convertToHTML')
  def _convertToHTML(self):
Jérome Perrin's avatar
Jérome Perrin committed
225
    """Convert the PDF text content to HTML with pdftohtml
226
    """
227
    if not self.hasData():
228
      return ''
229
    tmp = tempfile.NamedTemporaryFile()
230
    tmp.write(self.getData())
231
    tmp.seek(0)
232

Nicolas Dumazet's avatar
Nicolas Dumazet committed
233 234 235 236 237 238 239 240 241 242 243 244 245
    command_result = None
    try:
      command = ['pdftohtml', '-enc', 'UTF-8', '-stdout',
                 '-noframes', '-i', tmp.name]
      try:
        command_result = Popen(command, stdout=PIPE).communicate()[0]
      except OSError, e:
        if e.errno == errno.ENOENT:
          raise ConversionError('pdftohtml was not found')
        raise

    finally:
      tmp.close()
246
    # Quick hack to remove bg color - XXX
Nicolas Dumazet's avatar
Nicolas Dumazet committed
247
    h = command_result.replace('<BODY bgcolor="#A0A0A0"', '<BODY ')
248 249 250
    # Make links relative
    h = h.replace('href="%s.html' % tmp.name.split(os.sep)[-1],
                                                          'href="asEntireHTML')
251 252
    return h

Jean-Paul Smets's avatar
Jean-Paul Smets committed
253 254
  security.declarePrivate('_convertToDJVU')
  def _convertToDJVU(self):
Jérome Perrin's avatar
Jérome Perrin committed
255
    """Convert the PDF text content to DJVU with pdf2djvu
Jean-Paul Smets's avatar
Jean-Paul Smets committed
256 257 258 259 260 261 262 263 264
    """
    if not self.hasData():
      return ''
    tmp = tempfile.NamedTemporaryFile()
    tmp.write(self.getData())
    tmp.seek(0)

    command_result = None
    try:
265
      command = ['pdf2djvu', tmp.name]
Jean-Paul Smets's avatar
Jean-Paul Smets committed
266 267 268 269 270 271 272 273 274 275 276
      try:
        command_result = Popen(command, stdout=PIPE).communicate()[0]
      except OSError, e:
        if e.errno == errno.ENOENT:
          raise ConversionError('pdf2djvu was not found')
        raise

    finally:
      tmp.close()
    return command_result

277 278
  security.declareProtected(Permissions.AccessContentsInformation, 'getContentInformation')
  def getContentInformation(self):
279
    """Returns the information about the PDF document with pdfinfo.
280
    """
281
    if not self.hasData():
282
      return {}
283
    try:
284
      return self._content_information.copy() # pylint: disable=access-member-before-definition
285 286
    except AttributeError:
      pass
287
    tmp = tempfile.NamedTemporaryFile()
288
    tmp.write(self.getData())
289
    tmp.seek(0)
Nicolas Dumazet's avatar
Nicolas Dumazet committed
290
    command_result = None
291
    try:
Nicolas Dumazet's avatar
Nicolas Dumazet committed
292

293
      # First, we use pdfinfo to get standard metadata
Nicolas Dumazet's avatar
Nicolas Dumazet committed
294 295 296 297 298 299 300 301
      command = ['pdfinfo', '-meta', '-box', tmp.name]
      try:
        command_result = Popen(command, stdout=PIPE).communicate()[0]
      except OSError, e:
        if e.errno == errno.ENOENT:
          raise ConversionError('pdfinfo was not found')
        raise

302
      result = {}
Nicolas Dumazet's avatar
Nicolas Dumazet committed
303
      for line in command_result.splitlines():
304 305 306 307 308
        item_list = line.split(':')
        key = item_list[0].strip()
        value = ':'.join(item_list[1:]).strip()
        result[key] = value

Aurel's avatar
Aurel committed
309
      # Then we use PyPDF2 to get extra metadata
310
      try:
Aurel's avatar
Aurel committed
311 312
        from PyPDF2 import PdfFileReader
        from PyPDF2.utils import PdfReadError
313
      except ImportError:
Aurel's avatar
Aurel committed
314
        # if PyPDF2 not found, pass
315
        pass
316
      else:
317 318
        try:
          pdf_file = PdfFileReader(tmp)
319
          for info_key, info_value in (pdf_file.getDocumentInfo() or {}).iteritems():
320 321 322
            info_key = info_key.lstrip("/")
            if isinstance(info_value, unicode):
              info_value = info_value.encode("utf-8")
323 324 325 326

            # Ignore values that cannot be pickled ( such as AAPL:Keywords )
            try:
              pickle.dumps(info_value)
327
            except pickle.PicklingError:
328 329 330 331 332
              LOG("PDFDocument.getContentInformation", INFO,
                "Ignoring non picklable document info on %s: %s (%r)" % (
                self.getRelativeUrl(), info_key, info_value))
            else:
              result.setdefault(info_key, info_value)
333
        except (PdfReadError, AssertionError):
334
          LOG("PDFDocument.getContentInformation", PROBLEM,
Aurel's avatar
Aurel committed
335
            "PyPDF2 is Unable to read PDF, probably corrupted PDF here : %s" % \
336
            (self.getRelativeUrl(),))
337 338 339 340
        except Exception:
          # an exception of Exception class will be raised when the
          # document is encrypted.
          pass
341 342 343
    finally:
      tmp.close()

344 345
    # Store cache as an instance of document. FIXME: we usually try to avoid this
    # pattern and cache the result of methods using content md5 as a cache key.
346 347 348 349 350 351
    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
352
    except (AttributeError, KeyError):
353
      pass
354
    Image._setFile(self, data, precondition=precondition)