Source code for ciowarehouse.handlers.handler_pdf

"""A file handler for PDF file."""

from os import makedirs
from os.path import relpath, join, exists, dirname
from shutil import rmtree

from chrysalio.lib.utils import execute
from chrysalio.helpers.literal import Literal
from ..lib.i18n import _, translate
from ..lib.utils import THUMBNAIL_LARGE, THUMBNAIL_SMALL, make_file_id
from ..lib.handler import Handler


# =============================================================================
[docs]def includeme(configurator): """Function to include CioWarehouse a handler. :type configurator: pyramid.config.Configurator :param configurator: Object used to do configuration declaration within the application. """ Handler.register(configurator, HandlerPdf)
# =============================================================================
[docs]class HandlerPdf(Handler): """Class to manage a PDF file.""" uid = 'pdf' label = _('Generic PDF handling') extensions = ('.pdf',) viewings = ( {'name': 'pdf', 'label': _('Default'), 'template': 'ciowarehouse:Templates/handler_pdf_view.pt', 'css': ('/ciowarehouse/css/handler_pdf.css',)},) # -------------------------------------------------------------------------
[docs] def thumbnails( self, warehouse, abs_file, thumb_dir, request=None, registry=None): """Create the small and large thumbnail representing the file. See: :meth:`.lib.handler.Handler.thumbnails` """ if not warehouse.lock(abs_file): return if exists(thumb_dir): rmtree(thumb_dir) makedirs(thumb_dir, exist_ok=True) # Large thumbnail error = execute( ['nice', 'pdftocairo', '-r', '200', '-singlefile', '-jpeg', '-scale-to', str(warehouse.thumbnail_sizes[0][0]), abs_file, join(thumb_dir, THUMBNAIL_LARGE)], cwd=dirname(abs_file))[1] if error: self._log_error( _('Cannot create large thumbnail for PDF ${w}/${p}', { 'w': warehouse.uid, 'p': relpath(abs_file, warehouse.root)}), request) rmtree(thumb_dir) warehouse.unlock(abs_file) return # Small thumbnail execute([ 'nice', 'convert', join(thumb_dir, '{0}.jpg'.format(THUMBNAIL_LARGE)), '-geometry', '{0}x{1}>'.format(*warehouse.thumbnail_sizes[1]), join(thumb_dir, '{0}.jpg'.format(THUMBNAIL_SMALL))]) warehouse.unlock(abs_file)
# -------------------------------------------------------------------------
[docs] def view(self, request, warehouse, content=None, ts_factory=None): """Return a string containing HTML to display the file. See: :meth:`.lib.handler.Handler.view` """ path = join(*request.matchdict['path']) with open(join(dirname(__file__), '..', 'Static', 'Pdfjs', 'web', 'viewer_handler.html'), 'rb') as hdl: body = hdl.read().decode('utf8')\ .replace('_CLOSE_', self._route_close( request, make_file_id(join(warehouse.uid, path))))\ .replace("${_('Close')}", translate( _('Close'), request=request)) return self._chameleon_render( request, warehouse, self.viewings[0], ts_factory or _, {'content': Literal(body)})