Skip to content

Commit 22e8462

Browse files
committed
prevent UnicodeDecodeError when trying to decode pdf output as stderr
1 parent 695758f commit 22e8462

File tree

1 file changed

+12
-10
lines changed

1 file changed

+12
-10
lines changed

pdfkit/pdfkit.py

Lines changed: 12 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,6 @@
44
import sys
55
from .source import Source
66
from .configuration import Configuration
7-
from itertools import chain
87
import io
98
import codecs
109
try:
@@ -141,24 +140,28 @@ def to_pdf(self, path=None):
141140
input = None
142141
stdout, stderr = result.communicate(input=input)
143142
stderr = stderr or stdout
143+
try:
144+
stderr = stderr.decode('utf-8')
145+
except UnicodeDecodeError:
146+
stderr = ''
144147
exit_code = result.returncode
145148

146-
if 'cannot connect to X server' in stderr.decode('utf-8'):
149+
if 'cannot connect to X server' in stderr:
147150
raise IOError('%s\n'
148151
'You will need to run wkhtmltopdf within a "virtual" X server.\n'
149152
'Go to the link below for more information\n'
150-
'https://github.com/JazzCore/python-pdfkit/wiki/Using-wkhtmltopdf-without-X-server' % stderr.decode('utf-8'))
153+
'https://github.com/JazzCore/python-pdfkit/wiki/Using-wkhtmltopdf-without-X-server' % stderr)
151154

152-
if 'Error' in stderr.decode('utf-8'):
153-
raise IOError('wkhtmltopdf reported an error:\n' + stderr.decode('utf-8'))
155+
if 'Error' in stderr:
156+
raise IOError('wkhtmltopdf reported an error:\n' + stderr)
154157

155158
if exit_code != 0:
156-
raise IOError("wkhtmltopdf exited with non-zero code {0}. error:\n{1}".format(exit_code, stderr.decode("utf-8")))
159+
raise IOError("wkhtmltopdf exited with non-zero code {0}. error:\n{1}".format(exit_code, stderr))
157160

158161
# Since wkhtmltopdf sends its output to stderr we will capture it
159162
# and properly send to stdout
160163
if '--quiet' not in args:
161-
sys.stdout.write(stderr.decode('utf-8'))
164+
sys.stdout.write(stderr)
162165

163166
if not path:
164167
return stdout
@@ -184,18 +187,17 @@ def _normalize_options(self, options):
184187
:param options: dict {option name: value}
185188
186189
returns:
187-
iterator (option-key, option-value)
190+
iterator (option-key, option-value)
188191
- option names lower cased and prepended with
189192
'--' if necessary. Non-empty values cast to str
190193
"""
191-
normalized_options = {}
192194

193195
for key, value in list(options.items()):
194196
if not '--' in key:
195197
normalized_key = '--%s' % self._normalize_arg(key)
196198
else:
197199
normalized_key = self._normalize_arg(key)
198-
200+
199201
if isinstance(value, (list, tuple)):
200202
for optval in value:
201203
yield (normalized_key, optval)

0 commit comments

Comments
 (0)