Output Django Detail View as PDF (Japanese support)

This is a method to output Japanese PDF using Generic DetailView in Django.

I want to output PDF from template html, so I use a library called xhtml2pdf. Please note that only the dev version works with python3.

pip3 install --pre xhtml2pdf

First, prepare the Japanese font you want to use. Then place the fonts in <prj_name> / <prj_name> / static / fonts. After installation, pass the path to settings.py.

prj_name/prj_name/settings.py


BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, '<prj_name>', 'static')

Next, I will write a view. This time, as an example, the DetailView of model Foo of foo_app (<prj_name> / foos) is output as PDF. Use generic.DetailView to override only the render_to_response part.

prj_name/foos/views.py


import io
import os
from django.conf import settings
from django.views import generic
from django.http import HttpResponse
from django.template.loader import get_template
from xhtml2pdf import pisa

class FooPDFView(generic.DetailView):
    model = Foo
    template_name = 'foos/pdf.html'

    def render_to_response(self, context):
        html = get_template(self.template_name).render(self.get_context_data())
        result = io.BytesIO()
        pdf = pisa.pisaDocument(
            io.BytesIO(html.encode('utf-8')),
            result,
            link_callback=link_callback,
            encoding='utf-8',
        )

        if not pdf.err:
            return HttpResponse(
                result.getvalue(),
                content_type='application/pdf'
            )

        return HttpResponse('<pre>%s</pre>' % escape(html))

def link_callback(uri, rel):
    sUrl = settings.STATIC_URL
    sRoot = settings.STATIC_ROOT
    path = os.path.join(sRoot, uri.replace(sUrl, ""))

    if not os.path.isfile(path):
        raise Exception(
            '%s must start with %s' % \
            (uri, sUrl)
        )

    return path

I will write a template. Please note that if you do not set the font, Japanese will not be displayed as expected.

prj_name/foos/templates/foos/pdf.html


<!DOCTYPE html>{% load static %}
<html>
<head>
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
  <style type="text/css">
    @font-face {
      font-family: "japanese";
      src: url("{% static 'fonts/<your_font>.ttf' %}");
    }
    @page {
      size: A4;
      font-family: "japanese";
    }
    html, body {
      font-family: "japanese";
    }
  </style>
</head>
<body>
  <div>
name{{ object.name }}
  </div>
</body>
</html>

Set the urls.

prj_name/foos/urls.py


app_name = 'foos'
urlpatterns = [
    url(r'^(?P<pk>[0-9]+)/pdf/$',views.FooPDFView.as_view(), name='foo-pdf'),
]

Go through the project urls.

prj_name/prj_name/urls.py


urlpatterns = [
    url(r'^foos/', include('foos.urls')),
]

Now when you access / foos /: foo_id / pdf, you should get a PDF.

Recommended Posts

Output Django Detail View as PDF (Japanese support)
Japanese support for Jupyter PDF output (December 2020 version)
Django function-based view
Django class-based view
The story that Japanese output was confused with Django