HTML/CSSでデザインされたページをPDFに変換する
事前準備
以下のビルドパックをHerokuにインストール
myproject/myproject/myapp/settings.py
PDF_OPTIONS = {
'page-size': 'A4',
'orientation': 'Portrait',
'margin-top': '0.4in',
'margin-right': '0.4in',
'margin-bottom': '0.4in',
'margin-left': '0.4in',
'encoding': "UTF-8",
'no-outline': None,
'header-right': '[page] / [toPage]ページ'
}
myproject/myapp/myapp/views.py
from django.conf import settings
from django.views.generic import ListView
import pdfkit
from django.template import Context
from django.template.loader import render_to_string
class MyModelPdfView(ListView):
model = MyModel
def get(self, request, *args, **kwargs):
object_list = MyModel.objects.all()
context = {
'object_list': object_list,
}
t = render_to_string('myapp/pdf.html', context)
if 'DYNO' in os.environ:
print("environ:DYNO")
config = pdfkit.configuration(wkhtmltopdf='/app/bin/wkhtmltopdf')
pdf_buf = pdfkit.from_string(t, False, configuration=config, options=settings.PDF_OPTIONS)
else:
pdf_buf = pdfkit.from_string(t, False, options=settings.PDF_OPTIONS)
response = HttpResponse(pdf_buf, content_type='application/pdf') # Generates the response as pdf response.
response['Content-Disposition'] = 'attachment; filename=output.pdf'
return response