N
N
nurzhannogerbek2017-05-25 12:42:29
Django
nurzhannogerbek, 2017-05-25 12:42:29

How to properly create a pdf file with WeasyPrint | Django?

Hello! Please help me figure it out! I 'm trying to create a pdf using the WeasyPrint
application . Used the following code but it threw an error. It looks like this line of code throws an error: . What did I miss? How to fix the error? views.py:output = open(output.name, 'r')

from django.template.loader import render_to_string
from django.shortcuts import get_object_or_404
from django.http import HttpResponse
from weasyprint import HTML
import tempfile

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 in the console, PyCharm gives this warning:
WARNING: @font-face is currently not supported on Windows

Answer the question

In order to leave comments, you need to log in

2 answer(s)
D
devel787, 2017-05-29
@devel787

> Using the WeasyPrint application, I am trying to create a pdf file.
You might be more comfortable using https://github.com/arachnys/athenapdf

B
BelKir, 2017-11-28
@BelKir

Try this:
output = open(output.name, 'rb')
This should work, since you have a binary response returned

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question