S
S
Salavat Sharapov2014-09-08 20:03:22
Django
Salavat Sharapov, 2014-09-08 20:03:22

How to simplify code when generating PDF?

Good time of the day!
view.py:

......
/*Генерация pdf и сохранения его на сервере*/
result_pdf = open("%s%s.pdf" % (settings.MEDIA_ROOT, doc.title), 'wb')
pdf = pisa.CreatePDF(StringIO.StringIO(html.encode("UTF-8")), result_pdf, encoding='UTF-8')
result_pdf.close()

/*Генерация pdf для выдачи в response*/
result_response = StringIO.StringIO()
pdf_for_response = pisa.CreatePDF(StringIO.StringIO(html.encode("UTF-8")), result_response, encoding='UTF-8')
response['Content-Disposition'] = 'filename=test.pdf'
return response
....

How can the code be simplified?
Namely, I would not want to use CreatePDF twice.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
Y
yttrium, 2014-09-08
@desperadik

learn python!!
generalize. define a function:

def create_pdf(target):
    return pisa.CreatePDF(StringIO.StringIO(html.encode("UTF-8")), target, encoding='UTF-8')

homework:
how to call a function?

S
Salavat Sharapov, 2014-09-09
@desperadik

@qmax , @yttrium . THANK YOU for kicking!

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question