Commit b55dc47c authored by Tristan Cavelier's avatar Tristan Cavelier Committed by Cédric Le Ninivin

wkhtmltopdf: add basic handler + test

/reviewed-on nexedi/cloudooo!6
parent 5ad78541
##############################################################################
#
# Copyright (c) 2016 Nexedi SA and Contributors. All Rights Reserved.
#
# WARNING: This program as such is intended to be used by professional
# programmers who take the whole responsibility 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
# guarantees 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 zope.interface import implements
from cloudooo.interfaces.handler import IHandler
from cloudooo.file import File
from cloudooo.util import logger
from subprocess import Popen, PIPE
from tempfile import mktemp
class Handler(object):
"""ImageMagic Handler is used to handler images."""
implements(IHandler)
def __init__(self, base_folder_url, data, source_format, **kw):
""" Load pdf document """
self.base_folder_url = base_folder_url
self.file = File(base_folder_url, data, source_format)
self.environment = kw.get("env", {})
def convert(self, destination_format=None, **kw):
"""Convert a image"""
logger.debug("wkhtmltopdf convert: %s > %s" % (self.file.source_format, destination_format))
output_url = mktemp(
suffix='.%s' % destination_format,
dir=self.base_folder_url,
)
command = ["wkhtmltopdf", self.file.getUrl(), output_url]
stdout, stderr = Popen(
command,
stdout=PIPE,
stderr=PIPE,
close_fds=True,
env=self.environment,
).communicate()
self.file.reload(output_url)
try:
return self.file.getContent()
finally:
self.file.trash()
def getMetadata(self, base_document=False):
"""Returns a dictionary with all metadata of document.
along with the metadata.
"""
return NotImplementedError
def setMetadata(self, metadata={}):
"""Returns image with new metadata.
Keyword arguments:
metadata -- expected an dictionary with metadata.
"""
raise NotImplementedError
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Test Title With PNG Data URL</title>
</head>
<body>
<p>Hello</p>
<img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABYAAAAWCAYAAADEtGw7AAAAAXNSR0IArs4c6QAAAAZiS0dEAP8A/wD/oL2nkwAAAAlwSFlzAAALEwAACxMBAJqcGAAAAAd0SU1FB9oKGhI2GfiwdBgAAASJSURBVDjLnVVdbFRFGD0zc+/+sOy22y20SqkPSGkRWkDUtBEjJMSkiQmQmGA0fdJHNRITEt99FR9MIIZoYkzECAkmUC0hQQsi2JaCbWptu92W0u2W7t+93bt378/M5wNQmoYCepLJTCYzJ/N93znfAE+Bnp6eR+7btr3qHYb/gBMnTrwlhJjq6uqylFKt4XD4lG3bCIfDTyZ2HVuAiQCAAIAggM2e5+3N5/NHI5HI2kgkAqUUAEAplYhEIvnHvubIkSOsaJgfukb2nOt6A67rzjmOQ7ZtU7lcJtu2ybZtWS6XlWVZ0rIsKhaL76/Gxx8sWlpaYJrmLuXLTl/6O6WUdUopYowR55w45ySlZFJK+L7PpJTQNO3QasQaAJw/f76pubn5S9Mw9tRVbwAHAYyDiJaHDcbY0lBKke/7e55UPL2vr88lItq5Ywcp12aS6yCih6Hxe8FJKeE4DugepOC8rSaR+Hslsbg/q87OzmhNTU1HOBSCxhiYpoMxtkRIRFBSouIy3C5kMZUtskyhhGvjKWNDR2Oyv7vXWEnMAISklDPt7e1dnufptfFqQGhgjMH3fRARiAi5RQtf/XkMY1Y3Jo1rmCoOsvnF0VdnC+PvRVueWzN7PXmpev9HqExeh7gvqYaxsTHt4MGDzbqub1pfWwMFDiklOOfgjOP2wiQ+PfMNRCSL6toAFDSU3QymF1JsdCoVEEy8LmvfCOd+OX7xgSocAJ7v+7GTJ092A2CO4xARQYh7mSqaBXze8xnCVf9gfZ2JYDiHQGwIRqUAu+KAMc4YVyQ9cTSw59jby+WWBiBOnz49Oj09PW1XXM6kJCklPM/DzfFBzOTTcGwTTsVCapYweKsd0g0AMgSNheD5Dghc6Tr7oPHdH/hS8QCUAGwbHR2dfvPAgb1RoSC1IJSU6P3rJobmBkHwIJ0o+kcOYyy1H55tYn6uEbn5F7CG57CQeRahSEQR9O/4skLmASSHhoYqAwMD4yAFITSUyxYKZhRlS8C2BMYmEkinG+CV5jAxuRuzs8/DKCYwldwKEQgwPaDpmh4UfIX8bhDRncu9l5NKBEg6ZYBx1MfjIE+Hb0cxPtEBNzsBJ3sHlWwGjmnCsUpYG0sjWmVQcE2pFK+/WFlJLAGc6+39bcwVAWKeQ6FQCJueSUCQjpxpICTGYZsF2Okk7EwKjrkAv2zBMFpJsR28vnHm1vAXXxv8EW5cHBkZuZjL5STAGOMcTY0JvNhwCFaJYzFvolLIwDEW4Bl3QWYOIV1HbB3jdU3fu7GNvZ8sd95KGK3bWw9t39qckMQQCAZp364mduFXyZJpHYKDtKpqFozFEa5ZR5GaWla3MV+JJrIvX/r4j/GlJvQIzF+40PPzax2vbDZKFrvy+9X02bM//Xj1Su9UaPs7BzZs27u5bl28SgghfMXszHxmPnWu/7g50T3c1X8Y3+4+tfoPEo/H17e1tbWGw+Etw8PDZ2ZmZu4CiIFrL8W37Guoqt8UY4zplcW8n5/sSzm55CCA249t+g8c9xhwADqA0P2W8P+gadpTnnyYgH8B/3BW4MdlF5MAAAAASUVORK5CYII=" />
</body>
</html>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Test Title With Script</title>
<script>
window.addEventListener("load", function () {
document.querySelector("p").textContent = atob("V29ybGQ=");
});
</script>
</head>
<body>
<p>Hello</p>
</body>
</html>
##############################################################################
#
# Copyright (c) 2016 Nexedi SA and Contributors. All Rights Reserved.
#
# WARNING: This program as such is intended to be used by professional
# programmers who take the whole responsibility 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
# guarantees 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.
#
##############################################################################
import magic
from cloudooo.handler.wkhtmltopdf.handler import Handler
from cloudooo.tests.handlerTestCase import HandlerTestCase, make_suite
class TestHandler(HandlerTestCase):
def afterSetUp(self):
self.kw = dict(env=dict(PATH=self.env_path))
def testConvertHtmlWithPngDataUrlToPdf(self):
"""Test conversion of html with png data url to pdf"""
html_file = open("data/test_with_png_dataurl.html").read()
handler = Handler(self.tmp_url, html_file, "html", **self.kw)
pdf_file = handler.convert("pdf")
mime = magic.Magic(mime=True)
pdf_mimetype = mime.from_buffer(pdf_file)
self.assertEquals("application/pdf", pdf_mimetype)
def testConvertHtmlWithScriptToPdf(self):
"""Test conversion of html with script to pdf"""
html_file = open("data/test_with_script.html").read()
handler = Handler(self.tmp_url, html_file, "html", **self.kw)
pdf_file = handler.convert("pdf")
mime = magic.Magic(mime=True)
pdf_mimetype = mime.from_buffer(pdf_file)
self.assertEquals("application/pdf", pdf_mimetype)
# TODO: def testConvertHtmlWithHeaderAndFooter(self):
def testsetMetadata(self):
""" Test if metadata are inserted correclty """
handler = Handler(self.tmp_url, "", "png", **self.kw)
self.assertRaises(NotImplementedError, handler.setMetadata)
def test_suite():
return make_suite(TestHandler)
##############################################################################
#
# Copyright (c) 2016 Nexedi SA and Contributors. All Rights Reserved.
#
# WARNING: This program as such is intended to be used by professional
# programmers who take the whole responsibility 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
# guarantees 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 os.path import join
from cloudooo.tests.cloudoooTestCase import TestCase, make_suite
class TestServer(TestCase):
"""Test XmlRpc Server. Needs cloudooo server started"""
def ConversionScenarioList(self):
return [
(join('data', 'test_with_png_dataurl.html'), "html", "pdf", "application/pdf"),
(join('data', 'test_with_script.html'), "html", "pdf", "application/pdf"),
]
def testConvertHtmltoPdf(self):
"""Converts html to pdf"""
self.runConversionList(self.ConversionScenarioList())
def FaultConversionScenarioList(self):
return [
# Test to verify if server fail when a empty string is sent
('', '', ''),
# Try convert one html for a invalid format
(open(join('data', 'test_with_png_dataurl.html')).read(), 'html', 'xyz'),
]
def test_suite():
return make_suite(TestServer)
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