1

I use WeasyPrint app to generate pdf file in my django project.

I have next code which raise error. It seems to me that main problem in this line output = open(output.name, 'r'). I think user doen't have access rights. How to fix this problem?

views.py:

def generate_pdf(request, project_code):
    project = get_object_or_404(Project, pk=project_code, status='open')

    html_string = render_to_string('project/pdf.html', {'project': project})
    html = HTML(string=html_string)
    result = html.write_pdf()

    response = HttpResponse(content_type='application/pdf;')
    response['Content-Disposition'] = 'inline; filename=technical_specification.pdf'
    response['Content-Transfer-Encoding'] = 'binary'
    with tempfile.NamedTemporaryFile(delete=True) as output:
        output.write(result)
        output.flush()
        output = open(output.name, 'r')  <-- ERROR
        response.write(output.read())
    return response

ERROR:

Traceback (most recent call last):
  File "C:\Users\Nurzhan\AppData\Local\Programs\Python\Python35\lib\site-packages\django\core\handlers\exception.py", line 39, in inner
    response = get_response(request)
  File "C:\Users\Nurzhan\AppData\Local\Programs\Python\Python35\lib\site-packages\django\core\handlers\base.py", line 187, in _get_response
    response = self.process_exception_by_middleware(e, request)
  File "C:\Users\Nurzhan\AppData\Local\Programs\Python\Python35\lib\site-packages\django\core\handlers\base.py", line 185, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "C:\Users\Nurzhan\PycharmProjects\RMS\project\views.py", line 1808, in generate_pdf
    output = open(output.name, 'r')
PermissionError: [Errno 13] Permission denied: 'C:\\Users\\Nurzhan\\AppData\\Local\\Temp\\tmp_vx7wo99'

Also I have such WARNING:

WARNING: @font-face is currently not supported on Windows
Nurzhan Nogerbek
  • 4,806
  • 16
  • 87
  • 193

1 Answers1

3

Write and read a file is not needed for pdf output, you can just write it to the response:

def generate_pdf(request, project_code):
    project = get_object_or_404(Project, pk=project_code, status='open')
    template = loader.get_template('project/pdf.html')
    html = template.render(RequestContext(request, {'project': project}))
    response = HttpResponse(content_type='application/pdf')
    HTML(string=html).write_pdf(response)
    return response

If you really need to write it somewhere before the response try replacing output = open(output.name, 'r') with output.seek(0)

Meska
  • 181
  • 1
  • 6
  • Thank you! I used this article and solve my problem. Link: http://www.supinfo.com/articles/single/379-generate-pdf-files-out-of-html-templates-with-django – Nurzhan Nogerbek May 25 '17 at 14:15
  • 1
    Please provide references for loader, template and other packages you are using. – Hultan Jul 15 '21 at 08:42