buken
buken

Reputation: 206

Calling rst2pdf through subprocess in Django app truncates file

I'm using rst2pdf to generate a formatted pdf file in my Django app. This is the code I'm using to do this:

temp_file = tempfile.NamedTemporaryFile(mode='w+t', dir=PDF_PATH, delete=False)
temp_pdf = tempfile.NamedTemporaryFile(dir=PDF_PATH, delete=False)
temp_file.write(plaintext)

subprocess.call('rst2pdf ' + temp_file.name +' -s '+ STYLESHEET_PATH +' -o ' + temp_pdf.name, shell=True)
pdf = open(temp_pdf.name, 'rb')

response = HttpResponse(pdf.read(), mimetype='application/force-download')
response['Content-Disposition'] = 'attachment; filename=output.pdf'
response['Content-Length'] = os.stat(temp_pdf.name).st_size


return response

For some reason, the pdf that gets served as the response is truncated on the last page. The pdf on the filesystem is truncated. I can see the plaintext that's being written to the pdf, and it's all there. I even ran the same rst2pdf call on the command line with all the same arguments, and the pdf was generated fine. But for some reason, when I call rst2pdf from inside my Django app, the file is truncated. Any ideas on what can cause this, or on how I can debug the subprocess call?

Upvotes: 1

Views: 201

Answers (1)

buken
buken

Reputation: 206

It looks like I didn't fully understand how python handles writable files. Apparently after calling temp_file.write, there is still data in the buffer that doesn't get written out unless I call temp_file.close() or temp_file.flush().

Upvotes: 0

Related Questions