[Python-modules-commits] [django-wkhtmltopdf] 01/06: import django-wkhtmltopdf_3.1.0.orig.tar.gz

Scott Kitterman kitterman at moszumanska.debian.org
Thu Nov 10 20:21:39 UTC 2016


This is an automated email from the git hooks/post-receive script.

kitterman pushed a commit to branch master
in repository django-wkhtmltopdf.

commit c456aed4c286d3be784bfbd3b2fdd14790372a8f
Author: Scott Kitterman <scott at kitterman.com>
Date:   Thu Nov 10 13:53:58 2016 -0500

    import django-wkhtmltopdf_3.1.0.orig.tar.gz
---
 MANIFEST.in                                      |   2 +
 PKG-INFO                                         |  92 ++++++
 README.rst                                       |  69 +++++
 django_wkhtmltopdf.egg-info/PKG-INFO             |  92 ++++++
 django_wkhtmltopdf.egg-info/SOURCES.txt          |  21 ++
 django_wkhtmltopdf.egg-info/dependency_links.txt |   1 +
 django_wkhtmltopdf.egg-info/not-zip-safe         |   1 +
 django_wkhtmltopdf.egg-info/top_level.txt        |   1 +
 setup.cfg                                        |   8 +
 setup.py                                         |  33 +++
 wkhtmltopdf/__init__.py                          |   6 +
 wkhtmltopdf/models.py                            |   0
 wkhtmltopdf/subprocess.py                        |  44 +++
 wkhtmltopdf/tests/__init__.py                    |   0
 wkhtmltopdf/tests/models.py                      |   0
 wkhtmltopdf/tests/run.py                         |  59 ++++
 wkhtmltopdf/tests/templates/footer.html          |   4 +
 wkhtmltopdf/tests/templates/sample.html          |   7 +
 wkhtmltopdf/tests/templates/unicode.html         |   8 +
 wkhtmltopdf/tests/tests.py                       | 360 +++++++++++++++++++++++
 wkhtmltopdf/utils.py                             | 294 ++++++++++++++++++
 wkhtmltopdf/views.py                             | 156 ++++++++++
 22 files changed, 1258 insertions(+)

diff --git a/MANIFEST.in b/MANIFEST.in
new file mode 100644
index 0000000..df4289a
--- /dev/null
+++ b/MANIFEST.in
@@ -0,0 +1,2 @@
+include README.rst
+recursive-include * *.html
diff --git a/PKG-INFO b/PKG-INFO
new file mode 100644
index 0000000..fe41f25
--- /dev/null
+++ b/PKG-INFO
@@ -0,0 +1,92 @@
+Metadata-Version: 1.1
+Name: django-wkhtmltopdf
+Version: 3.1.0
+Summary: Converts HTML to PDF using wkhtmltopdf.
+Home-page: https://github.com/incuna/django-wkhtmltopdf
+Author: Incuna Ltd
+Author-email: admin at incuna.com
+License: MIT
+Description: django-wkhtmltopdf
+        ==================
+        
+        .. image:: https://badge.fury.io/py/django-wkhtmltopdf.png
+            :target: http://badge.fury.io/py/django-wkhtmltopdf
+            :alt: Latest version
+        
+        .. image:: https://travis-ci.org/incuna/django-wkhtmltopdf.png?branch=master
+           :target: https://travis-ci.org/incuna/django-wkhtmltopdf
+           :alt: Travis-CI
+        
+        .. image:: https://img.shields.io/pypi/dm/django-wkhtmltopdf.svg
+            :target: https://badge.fury.io/py/django-wkhtmltopdf
+            :alt: Number of PyPI downloads on a month
+        
+        
+        Converts HTML to PDF
+        --------------------
+        
+        Provides Django views to wrap the HTML to PDF conversion of the `wkhtmltopdf <http://wkhtmltopdf.org>`_ binary.
+        
+        Requirements
+        ------------
+        
+        Install the `wkhtmltopdf static binary <http://wkhtmltopdf.org/downloads.html>`_.
+        
+        This requires libfontconfig (on Ubuntu: ``sudo aptitude install libfontconfig``).
+        
+        Python 2.6+ and 3.3+ are supported.
+        
+        
+        Installation
+        ------------
+        
+        Run ``pip install django-wkhtmltopdf``.
+        
+        Add ``'wkhtmltopdf'`` to ``INSTALLED_APPS`` in your ``settings.py``.
+        
+        By default it will execute the first ``wkhtmltopdf`` command found on your ``PATH``.
+        
+        If you can't add wkhtmltopdf to your ``PATH``, you can set ``WKHTMLTOPDF_CMD`` to a
+        specific executable:
+        
+        e.g. in ``settings.py``: ::
+        
+            WKHTMLTOPDF_CMD = '/path/to/my/wkhtmltopdf'
+        
+        or alternatively as env variable: ::
+        
+            export WKHTMLTOPDF_CMD=/path/to/my/wkhtmltopdf
+        
+        You may also set ``WKHTMLTOPDF_CMD_OPTIONS`` in ``settings.py`` to a dictionary
+        of default command-line options.
+        
+        The default is: ::
+        
+            WKHTMLTOPDF_CMD_OPTIONS = {
+                'quiet': True,
+            }
+        
+        Documentation
+        -------------
+        
+        Documentation is available at http://django-wkhtmltopdf.readthedocs.org/en/latest/.
+        
+        License
+        -------
+        
+        MIT licensed. See the bundled `LICENSE <https://github.com/incuna/django-wkhtmltopdf/blob/master/LICENSE>`_ file for more details.
+        
+Keywords: django wkhtmltopdf pdf
+Platform: UNKNOWN
+Classifier: Development Status :: 5 - Production/Stable
+Classifier: Environment :: Web Environment
+Classifier: Intended Audience :: Developers
+Classifier: Operating System :: OS Independent
+Classifier: License :: OSI Approved :: MIT License
+Classifier: Programming Language :: Python :: 2
+Classifier: Programming Language :: Python :: 2.6
+Classifier: Programming Language :: Python :: 2.7
+Classifier: Programming Language :: Python :: 3
+Classifier: Programming Language :: Python :: 3.3
+Classifier: Programming Language :: Python :: 3.4
+Classifier: Framework :: Django
diff --git a/README.rst b/README.rst
new file mode 100644
index 0000000..0593793
--- /dev/null
+++ b/README.rst
@@ -0,0 +1,69 @@
+django-wkhtmltopdf
+==================
+
+.. image:: https://badge.fury.io/py/django-wkhtmltopdf.png
+    :target: http://badge.fury.io/py/django-wkhtmltopdf
+    :alt: Latest version
+
+.. image:: https://travis-ci.org/incuna/django-wkhtmltopdf.png?branch=master
+   :target: https://travis-ci.org/incuna/django-wkhtmltopdf
+   :alt: Travis-CI
+
+.. image:: https://img.shields.io/pypi/dm/django-wkhtmltopdf.svg
+    :target: https://badge.fury.io/py/django-wkhtmltopdf
+    :alt: Number of PyPI downloads on a month
+
+
+Converts HTML to PDF
+--------------------
+
+Provides Django views to wrap the HTML to PDF conversion of the `wkhtmltopdf <http://wkhtmltopdf.org>`_ binary.
+
+Requirements
+------------
+
+Install the `wkhtmltopdf static binary <http://wkhtmltopdf.org/downloads.html>`_.
+
+This requires libfontconfig (on Ubuntu: ``sudo aptitude install libfontconfig``).
+
+Python 2.6+ and 3.3+ are supported.
+
+
+Installation
+------------
+
+Run ``pip install django-wkhtmltopdf``.
+
+Add ``'wkhtmltopdf'`` to ``INSTALLED_APPS`` in your ``settings.py``.
+
+By default it will execute the first ``wkhtmltopdf`` command found on your ``PATH``.
+
+If you can't add wkhtmltopdf to your ``PATH``, you can set ``WKHTMLTOPDF_CMD`` to a
+specific executable:
+
+e.g. in ``settings.py``: ::
+
+    WKHTMLTOPDF_CMD = '/path/to/my/wkhtmltopdf'
+
+or alternatively as env variable: ::
+
+    export WKHTMLTOPDF_CMD=/path/to/my/wkhtmltopdf
+
+You may also set ``WKHTMLTOPDF_CMD_OPTIONS`` in ``settings.py`` to a dictionary
+of default command-line options.
+
+The default is: ::
+
+    WKHTMLTOPDF_CMD_OPTIONS = {
+        'quiet': True,
+    }
+
+Documentation
+-------------
+
+Documentation is available at http://django-wkhtmltopdf.readthedocs.org/en/latest/.
+
+License
+-------
+
+MIT licensed. See the bundled `LICENSE <https://github.com/incuna/django-wkhtmltopdf/blob/master/LICENSE>`_ file for more details.
diff --git a/django_wkhtmltopdf.egg-info/PKG-INFO b/django_wkhtmltopdf.egg-info/PKG-INFO
new file mode 100644
index 0000000..fe41f25
--- /dev/null
+++ b/django_wkhtmltopdf.egg-info/PKG-INFO
@@ -0,0 +1,92 @@
+Metadata-Version: 1.1
+Name: django-wkhtmltopdf
+Version: 3.1.0
+Summary: Converts HTML to PDF using wkhtmltopdf.
+Home-page: https://github.com/incuna/django-wkhtmltopdf
+Author: Incuna Ltd
+Author-email: admin at incuna.com
+License: MIT
+Description: django-wkhtmltopdf
+        ==================
+        
+        .. image:: https://badge.fury.io/py/django-wkhtmltopdf.png
+            :target: http://badge.fury.io/py/django-wkhtmltopdf
+            :alt: Latest version
+        
+        .. image:: https://travis-ci.org/incuna/django-wkhtmltopdf.png?branch=master
+           :target: https://travis-ci.org/incuna/django-wkhtmltopdf
+           :alt: Travis-CI
+        
+        .. image:: https://img.shields.io/pypi/dm/django-wkhtmltopdf.svg
+            :target: https://badge.fury.io/py/django-wkhtmltopdf
+            :alt: Number of PyPI downloads on a month
+        
+        
+        Converts HTML to PDF
+        --------------------
+        
+        Provides Django views to wrap the HTML to PDF conversion of the `wkhtmltopdf <http://wkhtmltopdf.org>`_ binary.
+        
+        Requirements
+        ------------
+        
+        Install the `wkhtmltopdf static binary <http://wkhtmltopdf.org/downloads.html>`_.
+        
+        This requires libfontconfig (on Ubuntu: ``sudo aptitude install libfontconfig``).
+        
+        Python 2.6+ and 3.3+ are supported.
+        
+        
+        Installation
+        ------------
+        
+        Run ``pip install django-wkhtmltopdf``.
+        
+        Add ``'wkhtmltopdf'`` to ``INSTALLED_APPS`` in your ``settings.py``.
+        
+        By default it will execute the first ``wkhtmltopdf`` command found on your ``PATH``.
+        
+        If you can't add wkhtmltopdf to your ``PATH``, you can set ``WKHTMLTOPDF_CMD`` to a
+        specific executable:
+        
+        e.g. in ``settings.py``: ::
+        
+            WKHTMLTOPDF_CMD = '/path/to/my/wkhtmltopdf'
+        
+        or alternatively as env variable: ::
+        
+            export WKHTMLTOPDF_CMD=/path/to/my/wkhtmltopdf
+        
+        You may also set ``WKHTMLTOPDF_CMD_OPTIONS`` in ``settings.py`` to a dictionary
+        of default command-line options.
+        
+        The default is: ::
+        
+            WKHTMLTOPDF_CMD_OPTIONS = {
+                'quiet': True,
+            }
+        
+        Documentation
+        -------------
+        
+        Documentation is available at http://django-wkhtmltopdf.readthedocs.org/en/latest/.
+        
+        License
+        -------
+        
+        MIT licensed. See the bundled `LICENSE <https://github.com/incuna/django-wkhtmltopdf/blob/master/LICENSE>`_ file for more details.
+        
+Keywords: django wkhtmltopdf pdf
+Platform: UNKNOWN
+Classifier: Development Status :: 5 - Production/Stable
+Classifier: Environment :: Web Environment
+Classifier: Intended Audience :: Developers
+Classifier: Operating System :: OS Independent
+Classifier: License :: OSI Approved :: MIT License
+Classifier: Programming Language :: Python :: 2
+Classifier: Programming Language :: Python :: 2.6
+Classifier: Programming Language :: Python :: 2.7
+Classifier: Programming Language :: Python :: 3
+Classifier: Programming Language :: Python :: 3.3
+Classifier: Programming Language :: Python :: 3.4
+Classifier: Framework :: Django
diff --git a/django_wkhtmltopdf.egg-info/SOURCES.txt b/django_wkhtmltopdf.egg-info/SOURCES.txt
new file mode 100644
index 0000000..f4a0e9b
--- /dev/null
+++ b/django_wkhtmltopdf.egg-info/SOURCES.txt
@@ -0,0 +1,21 @@
+MANIFEST.in
+README.rst
+setup.cfg
+setup.py
+django_wkhtmltopdf.egg-info/PKG-INFO
+django_wkhtmltopdf.egg-info/SOURCES.txt
+django_wkhtmltopdf.egg-info/dependency_links.txt
+django_wkhtmltopdf.egg-info/not-zip-safe
+django_wkhtmltopdf.egg-info/top_level.txt
+wkhtmltopdf/__init__.py
+wkhtmltopdf/models.py
+wkhtmltopdf/subprocess.py
+wkhtmltopdf/utils.py
+wkhtmltopdf/views.py
+wkhtmltopdf/tests/__init__.py
+wkhtmltopdf/tests/models.py
+wkhtmltopdf/tests/run.py
+wkhtmltopdf/tests/tests.py
+wkhtmltopdf/tests/templates/footer.html
+wkhtmltopdf/tests/templates/sample.html
+wkhtmltopdf/tests/templates/unicode.html
\ No newline at end of file
diff --git a/django_wkhtmltopdf.egg-info/dependency_links.txt b/django_wkhtmltopdf.egg-info/dependency_links.txt
new file mode 100644
index 0000000..8b13789
--- /dev/null
+++ b/django_wkhtmltopdf.egg-info/dependency_links.txt
@@ -0,0 +1 @@
+
diff --git a/django_wkhtmltopdf.egg-info/not-zip-safe b/django_wkhtmltopdf.egg-info/not-zip-safe
new file mode 100644
index 0000000..8b13789
--- /dev/null
+++ b/django_wkhtmltopdf.egg-info/not-zip-safe
@@ -0,0 +1 @@
+
diff --git a/django_wkhtmltopdf.egg-info/top_level.txt b/django_wkhtmltopdf.egg-info/top_level.txt
new file mode 100644
index 0000000..d01a0cc
--- /dev/null
+++ b/django_wkhtmltopdf.egg-info/top_level.txt
@@ -0,0 +1 @@
+wkhtmltopdf
diff --git a/setup.cfg b/setup.cfg
new file mode 100644
index 0000000..6f08d0e
--- /dev/null
+++ b/setup.cfg
@@ -0,0 +1,8 @@
+[bdist_wheel]
+universal = 1
+
+[egg_info]
+tag_build = 
+tag_date = 0
+tag_svn_revision = 0
+
diff --git a/setup.py b/setup.py
new file mode 100644
index 0000000..876e9ef
--- /dev/null
+++ b/setup.py
@@ -0,0 +1,33 @@
+from setuptools import setup, find_packages
+
+import wkhtmltopdf
+
+
+setup(
+    name='django-wkhtmltopdf',
+    packages=find_packages(),
+    include_package_data=True,
+    version=wkhtmltopdf.__version__,
+    description='Converts HTML to PDF using wkhtmltopdf.',
+    long_description=open('README.rst').read(),
+    license='MIT',
+    author=wkhtmltopdf.__author__,
+    author_email='admin at incuna.com',
+    url='https://github.com/incuna/django-wkhtmltopdf',
+    zip_safe=False,
+    classifiers=[
+        'Development Status :: 5 - Production/Stable',
+        'Environment :: Web Environment',
+        'Intended Audience :: Developers',
+        'Operating System :: OS Independent',
+        'License :: OSI Approved :: MIT License',
+        'Programming Language :: Python :: 2',
+        'Programming Language :: Python :: 2.6',
+        'Programming Language :: Python :: 2.7',
+        'Programming Language :: Python :: 3',
+        'Programming Language :: Python :: 3.3',
+        'Programming Language :: Python :: 3.4',
+        'Framework :: Django',
+    ],
+    keywords='django wkhtmltopdf pdf',
+)
diff --git a/wkhtmltopdf/__init__.py b/wkhtmltopdf/__init__.py
new file mode 100644
index 0000000..09186fa
--- /dev/null
+++ b/wkhtmltopdf/__init__.py
@@ -0,0 +1,6 @@
+import os
+if 'DJANGO_SETTINGS_MODULE' in os.environ:
+    from .utils import *
+
+__author__ = 'Incuna Ltd'
+__version__ = '3.1.0'
diff --git a/wkhtmltopdf/models.py b/wkhtmltopdf/models.py
new file mode 100644
index 0000000..e69de29
diff --git a/wkhtmltopdf/subprocess.py b/wkhtmltopdf/subprocess.py
new file mode 100644
index 0000000..d0abacd
--- /dev/null
+++ b/wkhtmltopdf/subprocess.py
@@ -0,0 +1,44 @@
+from __future__ import absolute_import
+
+from subprocess import *
+
+
+# Provide Python 2.7's check_output() function.
+try:
+    check_output
+except NameError:
+    def check_output(*popenargs, **kwargs):
+        r"""Run command with arguments and return its output as a byte string.
+
+        If the exit code was non-zero it raises a CalledProcessError.  The
+        CalledProcessError object will have the return code in the returncode
+        attribute and output in the output attribute.
+
+        The arguments are the same as for the Popen constructor.  Example:
+
+        >>> check_output(["ls", "-l", "/dev/null"])
+        'crw-rw-rw- 1 root root 1, 3 Oct 18  2007 /dev/null\n'
+
+        The stdout argument is not allowed as it is used internally.
+        To capture standard error in the result, use stderr=STDOUT.
+
+        >>> check_output(["/bin/sh", "-c",
+        ...               "ls -l non_existent_file ; exit 0"],
+        ...              stderr=STDOUT)
+        'ls: non_existent_file: No such file or directory\n'
+        """
+        if 'stdout' in kwargs:
+            raise ValueError('stdout argument not allowed, it will be overridden.')
+        process = Popen(stdout=PIPE, *popenargs, **kwargs)
+        output, unused_err = process.communicate()
+        retcode = process.poll()
+        if retcode:
+            cmd = kwargs.get("args")
+            if cmd is None:
+                cmd = popenargs[0]
+            error = CalledProcessError(retcode, cmd)
+            # Add the output attribute to CalledProcessError, which
+            # doesn't exist until Python 2.7.
+            error.output = output
+            raise error
+        return output
diff --git a/wkhtmltopdf/tests/__init__.py b/wkhtmltopdf/tests/__init__.py
new file mode 100644
index 0000000..e69de29
diff --git a/wkhtmltopdf/tests/models.py b/wkhtmltopdf/tests/models.py
new file mode 100644
index 0000000..e69de29
diff --git a/wkhtmltopdf/tests/run.py b/wkhtmltopdf/tests/run.py
new file mode 100644
index 0000000..4ff7f9e
--- /dev/null
+++ b/wkhtmltopdf/tests/run.py
@@ -0,0 +1,59 @@
+#! /usr/bin/env python
+import os
+import sys
+
+import django
+from django.conf import settings
+
+DIRNAME = os.path.abspath(os.path.dirname(__file__))
+
+sys.path.insert(0, os.getcwd())
+
+settings.configure(
+    DEBUG=False,
+    DATABASES={
+        'default': {
+            'ENGINE': 'django.db.backends.sqlite3',
+            'NAME': ':memory:',
+        }
+    },
+    INSTALLED_APPS=(
+        'django.contrib.contenttypes',
+        'wkhtmltopdf.tests',
+        'wkhtmltopdf',
+    ),
+    MIDDLEWARE_CLASSES=(
+        'django.middleware.common.CommonMiddleware',
+        'django.middleware.csrf.CsrfViewMiddleware',
+    ),
+    MEDIA_ROOT=os.path.join(DIRNAME, 'media'),
+    MEDIA_URL='/media/',
+    STATIC_ROOT=os.path.join(DIRNAME, 'static'),
+    STATIC_URL='/static/',
+    TEMPLATES = [  # For Django >= 1.10. Ignored in lower versions
+        {
+            'BACKEND': 'django.template.backends.django.DjangoTemplates',
+            'APP_DIRS': True,
+            'DIRS': [],
+            'OPTIONS': {},
+        },
+    ],
+    WKHTMLTOPDF_DEBUG=False,
+)
+
+try:
+    django.setup()
+except AttributeError:
+    pass  # Django < 1.7; okay to ignore
+
+
+try:
+    from django.test.runner import DiscoverRunner
+except ImportError:
+    from discover_runner.runner import DiscoverRunner
+
+
+test_runner = DiscoverRunner(verbosity=1)
+failures = test_runner.run_tests(['wkhtmltopdf'])
+if failures:
+    sys.exit(1)
diff --git a/wkhtmltopdf/tests/templates/footer.html b/wkhtmltopdf/tests/templates/footer.html
new file mode 100644
index 0000000..9deaf30
--- /dev/null
+++ b/wkhtmltopdf/tests/templates/footer.html
@@ -0,0 +1,4 @@
+{% load static %}
+<script src="{% static 'sample_js_not_existing.js' %}"></script>
+
+<img src="{% get_media_prefix %}sample_image_not_existing.png" />
diff --git a/wkhtmltopdf/tests/templates/sample.html b/wkhtmltopdf/tests/templates/sample.html
new file mode 100644
index 0000000..3dfbdbb
--- /dev/null
+++ b/wkhtmltopdf/tests/templates/sample.html
@@ -0,0 +1,7 @@
+<html>
+    <head>
+    </head>
+    <body>
+        <h1>{{ title }}</h1>
+    </body>
+</html>
diff --git a/wkhtmltopdf/tests/templates/unicode.html b/wkhtmltopdf/tests/templates/unicode.html
new file mode 100644
index 0000000..62968bb
--- /dev/null
+++ b/wkhtmltopdf/tests/templates/unicode.html
@@ -0,0 +1,8 @@
+<html>
+    <head>
+        <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
+    </head>
+    <body>
+        <h1>☃</h1>
+    </body>
+</html>
diff --git a/wkhtmltopdf/tests/tests.py b/wkhtmltopdf/tests/tests.py
new file mode 100644
index 0000000..7b48421
--- /dev/null
+++ b/wkhtmltopdf/tests/tests.py
@@ -0,0 +1,360 @@
+# -*- coding: utf-8 -*-
+
+from __future__ import absolute_import
+
+import os
+import sys
+
+from django.conf import settings
+from django.template import loader, RequestContext
+from django.test import TestCase
+from django.test.client import RequestFactory
+from django.utils import six
+from django.utils.encoding import smart_str
+
+from wkhtmltopdf.subprocess import CalledProcessError
+from wkhtmltopdf.utils import (_options_to_args, make_absolute_paths,
+                               wkhtmltopdf, render_to_temporary_file,
+                               RenderedFile)
+from wkhtmltopdf.views import PDFResponse, PDFTemplateView, PDFTemplateResponse
+
+
+class UnicodeContentPDFTemplateView(PDFTemplateView):
+    """
+    PDFTemplateView with the addition of unicode content in his context.
+
+    Used in unicode content view testing.
+    """
+    def get_context_data(self, **kwargs):
+        Base = super(UnicodeContentPDFTemplateView, self)
+        context = Base.get_context_data(**kwargs)
+        context['title'] = u'♥'
+        return context
+
+
+class TestUtils(TestCase):
+    def setUp(self):
+        # Clear standard error
+        self._stderr = sys.stderr
+        sys.stderr = open(os.devnull, 'w')
+        self.factory = RequestFactory()
+
+    def tearDown(self):
+        sys.stderr = self._stderr
+
+    def test_options_to_args(self):
+        self.assertEqual(_options_to_args(), [])
+        self.assertEqual(_options_to_args(heart=u'♥', verbose=True,
+                                          file_name='file-name'),
+                         ['--file-name', 'file-name',
+                          '--heart', u'♥',
+                          '--verbose'])
+
+    def test_wkhtmltopdf(self):
+        """Should run wkhtmltopdf to generate a PDF"""
+        title = 'A test template.'
+        template = loader.get_template('sample.html')
+        temp_file = render_to_temporary_file(template, context={'title': title})
+        try:
+            # Standard call
+            pdf_output = wkhtmltopdf(pages=[temp_file.name])
+            self.assertTrue(pdf_output.startswith(b'%PDF'), pdf_output)
+
+            # Single page
+            pdf_output = wkhtmltopdf(pages=temp_file.name)
+            self.assertTrue(pdf_output.startswith(b'%PDF'), pdf_output)
+
+            # Unicode
+            pdf_output = wkhtmltopdf(pages=[temp_file.name], title=u'♥')
+            self.assertTrue(pdf_output.startswith(b'%PDF'), pdf_output)
+
+            # Invalid arguments
+            self.assertRaises(CalledProcessError,
+                              wkhtmltopdf, pages=[])
+        finally:
+            temp_file.close()
+
+    def test_wkhtmltopdf_with_unicode_content(self):
+        """A wkhtmltopdf call should render unicode content properly"""
+        title = u'♥'
+        template = loader.get_template('unicode.html')
+        temp_file = render_to_temporary_file(template, context={'title': title})
+        try:
+            pdf_output = wkhtmltopdf(pages=[temp_file.name])
+            self.assertTrue(pdf_output.startswith(b'%PDF'), pdf_output)
+        finally:
+            temp_file.close()
+
+    def test_render_to_temporary_file(self):
+        """Should render a template to a temporary file."""
+        title = 'A test template.'
+
+        template = loader.get_template('sample.html')
+        temp_file = render_to_temporary_file(template, context={'title': title})
+        temp_file.seek(0)
+        saved_content = smart_str(temp_file.read())
+        self.assertTrue(title in saved_content)
+        temp_file.close()
+
+    def _render_file(self, template, context):
+        """Helper method for testing rendered file deleted/persists tests."""
+        render = RenderedFile(template=template, context=context)
+        render.temporary_file.seek(0)
+        saved_content = smart_str(render.temporary_file.read())
+
+        return (saved_content, render.filename)
+
+    def test_rendered_file_deleted_on_production(self):
+        """If WKHTMLTOPDF_DEBUG=False, delete rendered file on object close."""
+        title = 'A test template.'
+        template = loader.get_template('sample.html')
+        debug = getattr(settings, 'WKHTMLTOPDF_DEBUG', settings.DEBUG)
+
+        saved_content, filename = self._render_file(template=template,
+                                                    context={'title': title})
+        # First verify temp file was rendered correctly.
+        self.assertTrue(title in saved_content)
+
+        # Then check if file is deleted when debug=False.
+        self.assertFalse(debug)
+        self.assertFalse(os.path.isfile(filename))
+
+    def test_rendered_file_persists_on_debug(self):
+        """If WKHTMLTOPDF_DEBUG=True, the rendered file should persist."""
+        title = 'A test template.'
+        template = loader.get_template('sample.html')
+        with self.settings(WKHTMLTOPDF_DEBUG=True):
+            debug = getattr(settings, 'WKHTMLTOPDF_DEBUG', settings.DEBUG)
+
+            saved_content, filename = self._render_file(template=template,
+                                                    context={'title': title})
+            # First verify temp file was rendered correctly.
+            self.assertTrue(title in saved_content)
+
+            # Then check if file persists when debug=True.
+            self.assertTrue(debug)
+            self.assertTrue(os.path.isfile(filename))
+
+
+class TestViews(TestCase):
+    template = 'sample.html'
+    footer_template = 'footer.html'
+    pdf_filename = 'output.pdf'
+    attached_fileheader = 'attachment; filename="{0}"'
+    inline_fileheader = 'inline; filename="{0}"'
+
+    def test_pdf_response(self):
+        """Should generate correct HttpResponse object and content type."""
+        # 404
+        response = PDFResponse(content='', status=404)
+        self.assertEqual(response.status_code, 404)
+        self.assertEqual(response.content, b'')
+        self.assertEqual(response['Content-Type'], 'application/pdf')
+        self.assertFalse(response.has_header('Content-Disposition'))
+
+        content = b'%PDF-1.4\n%%EOF'
+        # Without filename
+        response = PDFResponse(content=content)
+        self.assertEqual(response.status_code, 200)
+        self.assertEqual(response.content, content)
+        self.assertEqual(response['Content-Type'], 'application/pdf')
+        self.assertFalse(response.has_header('Content-Disposition'))
+
+        # With filename
+        response = PDFResponse(content=content, filename="nospace.pdf")
+        self.assertEqual(response['Content-Disposition'],
+                         'attachment; filename="nospace.pdf"')
+        response = PDFResponse(content=content, filename="one space.pdf")
+        self.assertEqual(response['Content-Disposition'],
+                         'attachment; filename="one space.pdf"')
+        response = PDFResponse(content=content, filename="4'5\".pdf")
+        self.assertEqual(response['Content-Disposition'],
+                         'attachment; filename="4\'5.pdf"')
+        response = PDFResponse(content=content, filename=u"♥.pdf")
+        try:
+            import unidecode
+        except ImportError:
+            filename = '?.pdf'
+        else:
+            filename = '.pdf'
+        self.assertEqual(response['Content-Disposition'],
+                         'attachment; filename="{0}"'.format(filename))
+
+        # Content as a direct output
+        response = PDFResponse(content=content, filename="nospace.pdf",
+            show_content_in_browser=True)
+        self.assertEqual(response['Content-Disposition'],
+                         'inline; filename="nospace.pdf"')
+        response = PDFResponse(content=content, filename="one space.pdf",
+            show_content_in_browser=True)
+        self.assertEqual(response['Content-Disposition'],
+                         'inline; filename="one space.pdf"')
+        response = PDFResponse(content=content, filename="4'5\".pdf",
+            show_content_in_browser=True)
+        self.assertEqual(response['Content-Disposition'],
+                         'inline; filename="4\'5.pdf"')
+        response = PDFResponse(content=content, filename=u"♥.pdf",
+            show_content_in_browser=True)
+        try:
+            import unidecode
+        except ImportError:
+            filename = '?.pdf'
+        else:
+            filename = '.pdf'
+        self.assertEqual(response['Content-Disposition'],
+                         'inline; filename="{0}"'.format(filename))
+
+        # Content-Type
+        response = PDFResponse(content=content,
+                               content_type='application/x-pdf')
+        self.assertEqual(response['Content-Type'], 'application/x-pdf')
+
+    def test_pdf_template_response(self, show_content=False):
+        """Test PDFTemplateResponse."""
+
+        context = {'title': 'Heading'}
+        request = RequestFactory().get('/')
+        response = PDFTemplateResponse(request=request,
+                                       template=self.template,
+                                       context=context,
+                                       show_content_in_browser=show_content)
+        self.assertEqual(response._request, request)
+        self.assertEqual(response.template_name, self.template)
+        self.assertEqual(response.context_data, context)
+        self.assertEqual(response.filename, None)
+        self.assertEqual(response.header_template, None)
+        self.assertEqual(response.footer_template, None)
+        self.assertEqual(response.cmd_options, {})
+        self.assertFalse(response.has_header('Content-Disposition'))
+
+        # Render to temporary file
+        template = loader.get_template(self.template)
+        tempfile = render_to_temporary_file(template, context=context)
+        tempfile.seek(0)
+        html_content = smart_str(tempfile.read())
+        self.assertTrue(html_content.startswith('<html>'))
+        self.assertTrue('<h1>{title}</h1>'.format(**context)
+                        in html_content)
+
+        pdf_content = response.rendered_content
+        self.assertTrue(pdf_content.startswith(b'%PDF-'))
+        self.assertTrue(pdf_content.endswith(b'%%EOF\n'))
+
+        # Footer
+        cmd_options = {'title': 'Test PDF'}
+        response = PDFTemplateResponse(request=request,
+                                       template=self.template,
+                                       context=context,
+                                       filename=self.pdf_filename,
+                                       show_content_in_browser=show_content,
+                                       footer_template=self.footer_template,
+                                       cmd_options=cmd_options)
+        self.assertEqual(response.filename, self.pdf_filename)
+        self.assertEqual(response.header_template, None)
+        self.assertEqual(response.footer_template, self.footer_template)
+        self.assertEqual(response.cmd_options, cmd_options)
+        self.assertTrue(response.has_header('Content-Disposition'))
+
+        footer_template = loader.get_template(self.footer_template)
+        tempfile = render_to_temporary_file(footer_template, context=context,
+                                            request=request)
+        tempfile.seek(0)
+        footer_content = smart_str(tempfile.read())
+        footer_content = make_absolute_paths(footer_content)
+
+        media_url = 'file://{0}/'.format(settings.MEDIA_ROOT)
+        self.assertTrue(media_url in footer_content, True)
+
+        static_url = 'file://{0}/'.format(settings.STATIC_ROOT)
+        self.assertTrue(static_url in footer_content, True)
+
+        pdf_content = response.rendered_content
+        title = '\0'.join(cmd_options['title'])
+        self.assertIn(six.b(title), pdf_content)
+
+    def test_pdf_template_response_to_browser(self):
+        self.test_pdf_template_response(show_content=True)
+
+    def test_pdf_template_view(self, show_content=False):
+        """Test PDFTemplateView."""
+
+        view = PDFTemplateView.as_view(filename=self.pdf_filename,
+                                       show_content_in_browser=show_content,
+                                       template_name=self.template,
+                                       footer_template=self.footer_template)
+
+        # As PDF
+        request = RequestFactory().get('/')
+        response = view(request)
+        self.assertEqual(response.status_code, 200)
+        response.render()
+
+        fileheader = self.attached_fileheader
+        if show_content:
+            fileheader = self.inline_fileheader
+        self.assertEqual(response['Content-Disposition'],
+                         fileheader.format(self.pdf_filename))
+        self.assertTrue(response.content.startswith(b'%PDF-'))
+        self.assertTrue(response.content.endswith(b'%%EOF\n'))
+
+        # As HTML
+        request = RequestFactory().get('/?as=html')
+        response = view(request)
+        self.assertEqual(response.status_code, 200)
+        response.render()
+        self.assertFalse(response.has_header('Content-Disposition'))
+        self.assertTrue(response.content.startswith(b'<html>'))
+
+        # POST
+        request = RequestFactory().post('/')
+        response = view(request)
+        self.assertEqual(response.status_code, 405)
+
+    def test_pdf_template_view_to_browser(self):
+        self.test_pdf_template_view(show_content=True)
+
+    def test_pdf_template_view_unicode(self, show_content=False):
+        """Test PDFTemplateView with unicode content."""
+        view = UnicodeContentPDFTemplateView.as_view(
+            filename=self.pdf_filename,
+            show_content_in_browser=show_content,
+            template_name=self.template
+        )
+
+        # As PDF
+        request = RequestFactory().get('/')
+        response = view(request)
+        self.assertEqual(response.status_code, 200)
+        response.render()
+
+        fileheader = self.attached_fileheader
+        if show_content:
+            fileheader = self.inline_fileheader
+        self.assertEqual(response['Content-Disposition'],
+                         fileheader.format(self.pdf_filename))
+        # not sure how we can test this as the contents is all encoded...
+        # best we can do for the moment is check it's a pdf and it worked.
+        # self.assertTrue('☃' in response.content)
+        self.assertTrue(response.content.startswith(b'%PDF-'))
+        self.assertTrue(response.content.endswith(b'%%EOF\n'))
+
+    def test_pdf_template_view_unicode_to_browser(self):
+        self.test_pdf_template_view_unicode(show_content=True)
+
+    def test_get_cmd_options(self):
+        # Default cmd_options
+        view = PDFTemplateView()
+        self.assertEqual(view.cmd_options, PDFTemplateView.cmd_options)
+        self.assertEqual(PDFTemplateView.cmd_options, {})
+
+        # Instantiate with new cmd_options
+        cmd_options = {'orientation': 'landscape'}
+        view = PDFTemplateView(cmd_options=cmd_options)
+        self.assertEqual(view.cmd_options, cmd_options)
+        self.assertEqual(PDFTemplateView.cmd_options, {})
+
+        # Update local instance of cmd_options
+        view = PDFTemplateView()
+        view.cmd_options.update(cmd_options)
+        self.assertEqual(view.cmd_options, cmd_options)
+        self.assertEqual(PDFTemplateView.cmd_options, {})
diff --git a/wkhtmltopdf/utils.py b/wkhtmltopdf/utils.py
new file mode 100644
index 0000000..c871bd0
--- /dev/null
+++ b/wkhtmltopdf/utils.py
@@ -0,0 +1,294 @@
+from __future__ import absolute_import
+
+from copy import copy
+from itertools import chain
+import os
+import re
+import sys
+import shlex
+from tempfile import NamedTemporaryFile
+
+from django.utils.encoding import smart_text
+
+try:
+    from urllib.request import pathname2url
+    from urllib.parse import urljoin
+except ImportError:  # Python2
+    from urllib import pathname2url
+    from urlparse import urljoin
+
+import django
+from django.conf import settings
+from django.template.context import Context, RequestContext
+from django.utils import six
+
+from .subprocess import check_output
+
+
+def _options_to_args(**options):
+    """Converts ``options`` into a list of command-line arguments."""
+    flags = []
+    for name in sorted(options):
+        value = options[name]
+        if value is None:
+            continue
+        flags.append('--' + name.replace('_', '-'))
+        if value is not True:
+            flags.append(six.text_type(value))
+    return flags
+
+
+def wkhtmltopdf(pages, output=None, **kwargs):
+    """
+    Converts html to PDF using http://wkhtmltopdf.org/.
+
... 412 lines suppressed ...

-- 
Alioth's /usr/local/bin/git-commit-notice on /srv/git.debian.org/git/python-modules/packages/django-wkhtmltopdf.git



More information about the Python-modules-commits mailing list