52
loading...
This website collects cookies to deliver better user experience
Thanks for reading! - Content provided by App Generator.
Topics covered in this tutorial
app
that implements the PDF generation process. Complete beginners without a working project might find useful a dedicated Django tutorial that covers the Django basics: Django for Beginners. Install dependencies using a Virtual Environment
$ virtualenv env # create a VENV
$ source env/bin/activate # activate VENV
$
$ pip install reportlab
reportlab
is the library that brings all the PDF magic to our app. Let's use it and create a simple PDF document right in the Django shell:$ python ./manage.py shell # start Django CLI
>>>
>>> import reportlab # import the library
>>> from reportlab.pdfgen import canvas # import modules
>>> p = canvas.Canvas('1.pdf') # Init a PDF object
>>> p.drawString(200, 200, "Hello world.") # Draw a simple String
>>> p.showPage() # Create the PDF
>>> p.save() # Clean UP the library usage
>>> import os,sys
>>> os.startfile('1.pdf', 'open')
startfile
helper should open the PDF
file using the default handler registered in the operating system.$ # Current Dir: ROOT of the Django project
$ python manage.py startapp pdf_app
Code a simple PDF generator
# File contents: `app_pdf/views.py` (partial content)
...
from reportlab.pdfgen import canvas
from reportlab.lib.utils import ImageReader
from datetime import datetime
...
def pdf_dw(request):
# Create the HttpResponse object
response = HttpResponse(content_type='application/pdf')
# This line force a download
response['Content-Disposition'] = 'attachment; filename="1.pdf"'
# READ Optional GET param
get_param = request.GET.get('name', 'World')
# Generate unique timestamp
ts = datetime.utcnow().strftime('%Y-%m-%d %H:%M:%S.%f')
p = canvas.Canvas(response)
# Write content on the PDF
p.drawString(100, 500, "Hello " + get_param + " (Dynamic PDF) - " + ts )
# Close the PDF object.
p.showPage()
p.save()
# Show the result to the user
return response
HttpResponse
object returned to the user, read an optional GET parameter and generate a timestamp saved in the PDF. Once the new PDF is saved in memory, we can return the contents to the user. Sample Usage: http://localhost:8000/pdf_dw/?name=Bill Gates
reportlab
library we can generate PDF documents with embedded images without much effort - Let's see the code:# File contents: `app_pdf/views.py` (partial content)
...
from reportlab.pdfgen import canvas
from reportlab.lib.utils import ImageReader
from datetime import datetime
...
def pdf_img(request):
# Create the HttpResponse object with the appropriate PDF headers.
response = HttpResponse(content_type='application/pdf')
# Create the PDF object, using the response object as its "file."
p = canvas.Canvas(response)
my_image = ImageReader('https://www.google.com/images/srpr/logo11w.png')
p.drawImage(my_image, 10, 500, mask='auto')
# Close the PDF object.
p.showPage()
p.save()
# Show the result to the user
return response
my_image
object is the Google logo, downloaded from a public address and used in our PDF via drawImage
directive. Sample output served by http://localhost:8000/pdf_img/
# Update Django Settings.py
...
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'app_pdf',
]
...
Update Project Routing
urlpatterns = [
path('admin/', admin.site.urls),
path("" , include("app_pdf.urls")), # <-- NEW
]
Thanks for Reading! For questions related Django and PDF generation process, feel free to AMA in the comments section.
Thank you! 🚀🚀 Feel free to AMA in the comments section.