3

I'd like to convert a Django template to pdf file. An image in template :

<img src="{% static "img/person.png" }%" />

is changed to

<img src="/static/img/person.png" />

and It works well in browser.

But when I try to convert this html file to pdf file with Wkhtmltopdf module, there is an error :

$ wkhtmltopdf --javascript-delay 5000 report.html  report.pdf
Warning: Failed to load file:///static/img/person.png (ignore) 

It seems that Wkhtmltopdf module needs only absolute path.
If I set the src as a absolute path like :

<img src="/home/bingbong/django/project/apps/static/img/person.png" />

It works well but I know it is not a good way.

Is there any way to use static root path with Wkhtmltopdf?

How can I convert it successfully?


Edit

I am trying to follow this Creating PDFs with django (wkhtmltopdf)

But, there is a serious

Error: Failed loading page http://false (sometimes it will work just to ignore this error with --load-error-handling ignore)
Exit with code 1 due to network error: HostNotFoundError

subprocess.CalledProcessError: Command '['/usr/bin/wkhtmltopdf', '--encoding', 'utf8', '--javascript-delay', '1000', '--quiet', 'False', '/tmp/wkhtmltopdf3atfj280.html', '-']' returned non-zero exit status 1

I have no idea why http://false is there.

This is my urls.py

app_name = 'apps'
    urlpatterns =[
        url(r'^pdf/$', views.MyPDFView.as_view()),
] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)

This is my settings.py

STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'static')

WKHTMLTOPDF_CMD = '/usr/bin/wkhtmltopdf'

WKTHMLTOPDF_CMD_OPTIONS ={
    'quiet': False,
}

And this is MyPDFView class

class MyPDFView(View):
    template='apps/Report.html' # the template

    def get(self, request):

        response = PDFTemplateResponse(
            request=request,
            template=self.template,
            filename="apps/Report.pdf",
            show_content_in_browser=False,
            cmd_options={
                'javascript-delay':1000,
                'quiet':False,
            },
        )
        return response
BingbongKim
  • 549
  • 1
  • 6
  • 18

1 Answers1

0

I would recommend using Wkhtmltopdf in Django alongside something like django-wkhtmltopdf which will convert the static and media paths to absolute paths needed for the PDF.

laidibug
  • 1,179
  • 8
  • 5
  • I think I am using django-wkhtmltopdf. It still does not work. – BingbongKim Sep 19 '17 at 20:56
  • Are you using the PDFTemplateView? Is your STATIC_ROOT setup in local development? https://django-wkhtmltopdf.readthedocs.io/en/latest/installation.html#display-static-files – laidibug Sep 19 '17 at 22:04
  • yes, I am trying to follow the answer but there is another error. I edited the question. Could you check it please? – BingbongKim Sep 19 '17 at 23:26