1- import os
21import subprocess
2+ from pathlib import Path
33from tempfile import NamedTemporaryFile
4+
45from .version import VERSION
56
7+ THIS_DIR = Path (__file__ ).parent .resolve ()
8+ WK_PATH = THIS_DIR / 'bin' / 'wkhtmltopdf'
9+
610
711def execute_wk (* args ):
812 """
@@ -11,14 +15,7 @@ def execute_wk(*args):
1115 :param args: args to pass straight to subprocess.Popen
1216 :return: stdout, stderr
1317 """
14- this_dir = os .path .dirname (__file__ )
15- wk_name = 'wkhtmltopdf'
16- wkhtmltopdf_default = os .path .join (this_dir , 'bin' , wk_name )
17- # Reference command
18- wkhtmltopdf_cmd = os .environ .get ('WKHTMLTOPDF_CMD' , wkhtmltopdf_default )
19- if not os .path .isfile (wkhtmltopdf_cmd ):
20- raise IOError ('wkhtmltopdf binary not found at %s' % wkhtmltopdf_cmd )
21- wk_args = (wkhtmltopdf_cmd ,) + args
18+ wk_args = (str (WK_PATH ),) + args
2219 p = subprocess .Popen (wk_args , stdout = subprocess .PIPE , stderr = subprocess .PIPE )
2320 stdout , stderr = p .communicate ()
2421 return stdout , stderr , p .returncode
@@ -100,22 +97,23 @@ def generate_pdf(source,
10097 cmd_args .extend ([arg_name , str (value )])
10198
10299 def gen_pdf (src , cmd_args ):
103- with NamedTemporaryFile (suffix = '.pdf' , mode = 'rb+ ' ) as pdf_file :
100+ with NamedTemporaryFile (suffix = '.pdf' , mode = 'rb' ) as pdf_file :
104101 cmd_args += [src , pdf_file .name ]
105102 _ , stderr , returncode = execute_wk (* cmd_args )
106103 pdf_file .seek (0 )
107104 pdf_string = pdf_file .read ()
108105 # it seems wkhtmltopdf's error codes can be false, we'll ignore them if we
109106 # seem to have generated a pdf
110- if returncode != 0 and pdf_string [:4 ] != '%PDF' :
111- raise IOError ('error running wkhtmltopdf, command: %r\n response: "%s"' % (cmd_args , stderr .strip ()))
107+ if returncode != 0 and pdf_string [:4 ] != b'%PDF' :
108+ raise RuntimeError ('error running wkhtmltopdf, command: {!r}\n '
109+ 'response: "{}"' .format (cmd_args , stderr .strip ()))
112110 return pdf_string
113111
114112 if is_url :
115113 return gen_pdf (source , cmd_args )
116114
117115 with NamedTemporaryFile (suffix = '.html' , mode = 'wb' ) as html_file :
118- html_file .write (source .encode ('utf8' ))
116+ html_file .write (source .encode ())
119117 html_file .flush ()
120118 html_file .seek (0 )
121119 return gen_pdf (html_file .name , cmd_args )
0 commit comments