Upgrade to Pro
— share decks privately, control downloads, hide ads and more …
Speaker Deck
Features
Speaker Deck
PRO
Sign in
Sign up for free
Search
Search
[Django] Generating PDF with PDFForm
Search
Sébastien Fievet
April 16, 2011
Programming
0
85
[Django] Generating PDF with PDFForm
Sébastien Fievet
April 16, 2011
Tweet
Share
More Decks by Sébastien Fievet
See All by Sébastien Fievet
Introduction to Flask
zyegfryed
0
60
Django Round-Up – Meetup Django CH #28
zyegfryed
0
58
Django Round-Up – Meetup Django CH #25
zyegfryed
0
54
Django Round-Up – Meetup Django CH #23
zyegfryed
0
50
Django Round-Up – Meetup Django CH #21
zyegfryed
0
67
Django Round-Up – Meetup Django CH #20
zyegfryed
0
65
Django Round-Up – Meetup Django CH #19
zyegfryed
2
85
[Django] URL prefix with runserver
zyegfryed
0
1.4k
[Django] RESTful API
zyegfryed
1
220
Other Decks in Programming
See All in Programming
The Modern View Layer Rails Deserves: A Vision For 2025 And Beyond @ RailsConf 2025, Philadelphia, PA
marcoroth
2
510
Railsアプリケーションと パフォーマンスチューニング ー 秒間5万リクエストの モバイルオーダーシステムを支える事例 ー Rubyセミナー 大阪
falcon8823
5
1.1k
AI駆動のマルチエージェントによる業務フロー自動化の設計と実践
h_okkah
0
180
AIともっと楽するE2Eテスト
myohei
7
2.8k
PostgreSQLのRow Level SecurityをPHPのORMで扱う Eloquent vs Doctrine #phpcon #track2
77web
2
540
20250704_教育事業におけるアジャイルなデータ基盤構築
hanon52_
5
840
なぜ「共通化」を考え、失敗を繰り返すのか
rinchoku
1
660
Startups on Rails in Past, Present and Future–Irina Nazarova, RailsConf 2025
irinanazarova
0
140
0626 Findy Product Manager LT Night_高田スライド_speaker deck用
mana_takada
0
180
ISUCON研修おかわり会 講義スライド
arfes0e2b3c
1
450
新メンバーも今日から大活躍!SREが支えるスケールし続ける組織のオンボーディング
honmarkhunt
5
7.7k
スタートアップの急成長を支えるプラットフォームエンジニアリングと組織戦略
sutochin26
1
6.2k
Featured
See All Featured
Imperfection Machines: The Place of Print at Facebook
scottboms
267
13k
The Illustrated Children's Guide to Kubernetes
chrisshort
48
50k
Building Better People: How to give real-time feedback that sticks.
wjessup
367
19k
Fight the Zombie Pattern Library - RWD Summit 2016
marcelosomers
233
17k
Evolution of real-time – Irina Nazarova, EuRuKo, 2024
irinanazarova
8
830
Measuring & Analyzing Core Web Vitals
bluesmoon
7
510
It's Worth the Effort
3n
185
28k
How to Think Like a Performance Engineer
csswizardry
25
1.7k
The Cult of Friendly URLs
andyhume
79
6.5k
Documentation Writing (for coders)
carmenintech
72
4.9k
Building a Modern Day E-commerce SEO Strategy
aleyda
42
7.4k
Gamification - CAS2011
davidbonilla
81
5.4k
Transcript
Generating PDF with PDFForm Sébastien Fievet Djangocong Marseille April 16,
2011
Case study: outputting “simple” PDFs
Simple things should remain simple
Focus on skills
Designer == templating
Developper == rendering
The solution ?
None
None
1
pip install fdfgen
from fdfgen import forge_fdf def fill_form(fields, src, pdftk_bin): ... fdf_stream
= forge_fdf(fdf_data_strings=fields) ...
Issue
Issue Breaks on accentuated character
“ ” Fork it, fix it, contribute it. -- a
DVCS convinced guy
2
aptitude install pdftk
pdftk <PDF input> dump_data_fields
pdftk <PDF input> fill_form <FDF file> output <PDF output> flatten
import subprocess ... def fill_form(fields, src, pdftk_bin): ... cmd =
' '.join([pdftk_bin, src, 'fill_form', '-', 'output', '-', 'flatten']) try: process = subprocess.Popen(cmd, stdin=subprocess.PIPE, stdout=subprocess.PIPE, shell=True) return process.communicate(input=fdf_stream) except OSError, e: return None, e
But...
But... utf8 support broken on Ubuntu 10.10(binary package, v1.41)
But... utf8 support broken on Ubuntu 10.10(binary package, v1.41) Use
the source luke (v1.44)
But... utf8 support broken on Ubuntu 10.10(binary package, v1.41) Use
the source luke (v1.44) wget && make && make install
3
Django template engine == The challenge
Template loading
Template loading PDFs are binary file
Template loading PDFs are binary file We don't care about
the file content
Template loading PDFs are binary file We don't care about
the file content But we ALWAYS need the template path
import codecs from django.template.loader import find_template def get_template(template_name): def strict_errors(exception):
raise exception def fake_strict_errors(exception): return (u'', -1) codecs.register_error('strict', fake_strict_errors) template, origin = find_template(template_name) codecs.register_error('strict', strict_errors) return template
from django.template import loader, Template ... def get_template_from_string(source, origin=None, name=None):
if name and name.endswith('.pdf'): return PdfTemplate('pdf', origin, name) return Template(source, origin, name) loader.get_template_from_string = get_template_from_string
Template origin * Paranoiac mode
Template origin TEMPLATE_DEBUG = True * Paranoiac mode
Template origin TEMPLATE_DEBUG = True Or monkey-patch make_origin * *
Paranoiac mode
Template rendering
Template rendering Custom rendering method Leveraging pdftk and FDFGen Use
a dedicated Template class
from django.template import Template ... class PdfTemplate(Template): def __init__(self, template_string,
origin=None, name='<Unknown Template>'): self.origin = origin def render(self, context): context = context.items() output, err = fill_form(context, self.origin.name) if err: raise PdfTemplateError(err) return output
https://gist.github.com/918403
4
Usage
from django.http import HttpResponse from pdf import get_template def pdf_view(request,
template_name='pdf/awesome.pdf'): context = { 'foo': 'bar', 'bar': 'baz', 'awesome': True, 'user': request.user, } response = HttpResponse(mimetype='application/pdf') response['Content-Disposition'] = 'attachment; filename=awesome.pdf' template = get_template(template_name) response.write(template.render(context)) return response
Demo
Questions?