Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions README.rst
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,15 @@ You can pass a list with multiple URLs or files:
pdfkit.from_url(['google.com', 'yandex.ru', 'engadget.com'], 'out.pdf')
pdfkit.from_file(['file1.html', 'file2.html'], 'out.pdf')

File paths can also be ``pathlib.Path`` objects, including entries in an input
list and the output, cover, CSS, and configured ``wkhtmltopdf`` paths:

.. code-block:: python

from pathlib import Path

pdfkit.from_file(Path('test.html'), Path('out.pdf'))

Also you can pass an opened file:

.. code-block:: python
Expand Down
3 changes: 2 additions & 1 deletion pdfkit/configuration.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
import os
import subprocess
import sys
from .source import _normalize_path
try:
FileNotFoundError
except NameError:
Expand All @@ -12,7 +13,7 @@ class Configuration(object):
def __init__(self, wkhtmltopdf='', meta_tag_prefix='pdfkit-', environ=''):
self.meta_tag_prefix = meta_tag_prefix

self.wkhtmltopdf = wkhtmltopdf
self.wkhtmltopdf = _normalize_path(wkhtmltopdf)

try:
if not self.wkhtmltopdf:
Expand Down
4 changes: 2 additions & 2 deletions pdfkit/pdfkit.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
import subprocess
import sys
from collections import OrderedDict
from .source import Source
from .source import Source, _normalize_path
from .configuration import Configuration
import io
import codecs
Expand Down Expand Up @@ -123,7 +123,7 @@ def _command(self, path=None):
yield '-'

def command(self, path=None):
return list(self._command(path))
return [_normalize_path(arg) for arg in self._command(path)]

@staticmethod
def handle_error(exit_code, stderr):
Expand Down
10 changes: 10 additions & 0 deletions pdfkit/source.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,12 +7,22 @@
unicode = type(u'')


def _normalize_path(path):
if hasattr(path, '__fspath__'):
return os.fsdecode(path)
return path


class Source(object):
def __init__(self, url_or_file, type_):
self.source = url_or_file
self.type = type_

if self.type == 'file':
if isinstance(self.source, list):
self.source = [_normalize_path(path) for path in self.source]
else:
self.source = _normalize_path(self.source)
self.checkFiles()

def isUrl(self):
Expand Down
78 changes: 78 additions & 0 deletions tests/pdfkit-tests.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@
import sys
import codecs
import unittest
from pathlib import Path
from unittest.mock import Mock, patch


if sys.version_info[0] == 2 and sys.version_info[1] == 7:
Expand All @@ -17,6 +19,82 @@
import pdfkit


class TestPathLikeFiles(unittest.TestCase):
"""Path handling without requiring a wkhtmltopdf installation."""

def setUp(self):
self.html = Path(TESTS_ROOT) / 'fixtures' / 'example.html'
self.css = Path(TESTS_ROOT) / 'fixtures' / 'example.css'
self.configuration = pdfkit.configuration(wkhtmltopdf=sys.executable)

def test_single_input_path(self):
kit = pdfkit.PDFKit(self.html, 'file', configuration=self.configuration)
self.assertEqual(kit.command()[-2:], [str(self.html), '-'])

def test_mixed_input_paths(self):
paths = [self.html, str(self.html)]
kit = pdfkit.PDFKit(paths, 'file', configuration=self.configuration)
self.assertEqual(kit.command()[-3:], [str(self.html), str(self.html), '-'])
self.assertIsInstance(paths[0], Path)

def test_custom_path_protocol(self):
class FilePath(object):
def __fspath__(self):
return os.fsencode(str(self.html))

path = FilePath()
path.html = self.html
kit = pdfkit.PDFKit(path, 'file', configuration=self.configuration)
self.assertEqual(kit.command()[-2:], [str(self.html), '-'])

def test_missing_input_path(self):
with self.assertRaises(IOError):
pdfkit.PDFKit(self.html / 'missing', 'file',
configuration=self.configuration)

def test_path_with_css(self):
kit = pdfkit.PDFKit(self.html, 'file', css=self.css,
configuration=self.configuration)
self.assertEqual(kit.command()[-2:], ['-', '-'])
self.assertIn('<style>', kit.source.to_s())
self.assertIn(self.css.read_text().strip(), kit.source.to_s())

def test_output_and_cover_paths(self):
output = self.html.with_suffix('.pdf')
kit = pdfkit.PDFKit('https://example.com', 'url', cover=self.html,
configuration=self.configuration)
self.assertEqual(kit.command(output)[-4:],
['cover', str(self.html), 'https://example.com', str(output)])

def test_executable_path(self):
config = pdfkit.configuration(wkhtmltopdf=Path(sys.executable))
kit = pdfkit.PDFKit('html', 'string', configuration=config)
self.assertEqual(kit.command()[0], sys.executable)

def test_file_objects_still_use_stdin(self):
with self.html.open() as source:
kit = pdfkit.PDFKit(source, 'file', configuration=self.configuration)
self.assertIs(kit.source.source, source)
self.assertEqual(kit.command()[-2:], ['-', '-'])

def test_from_file_passes_string_arguments(self):
process = Mock(returncode=0)
process.communicate.return_value = (b'%PDF-test', b'')
with patch('pdfkit.pdfkit.subprocess.Popen', return_value=process) as popen:
result = pdfkit.from_file(self.html, configuration=self.configuration)
self.assertEqual(result, b'%PDF-test')
self.assertEqual(popen.call_args[0][0][-2:], [str(self.html), '-'])
process.communicate.assert_called_once_with(input=None)

def test_output_failure_keeps_io_error(self):
output = self.html / 'missing.pdf'
process = Mock(returncode=0)
process.communicate.return_value = (b'', b'')
with patch('pdfkit.pdfkit.subprocess.Popen', return_value=process):
with self.assertRaisesRegex(IOError, 'Command failed:'):
pdfkit.from_file(self.html, output, configuration=self.configuration)


class TestPDFKitInitialization(unittest.TestCase):
"""Test init"""

Expand Down