Skip to content

Commit

Permalink
First and last commmit =]
Browse files Browse the repository at this point in the history
  • Loading branch information
rodrigoddc committed May 20, 2020
0 parents commit 1af052a
Show file tree
Hide file tree
Showing 27 changed files with 504 additions and 0 deletions.
10 changes: 10 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
media
.idea
*.*~
*.sqlite3
*.pyc
.env
venv
__pycache__
local_settings.py
dev_settings.py
40 changes: 40 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
# Django exporting PDF
Simple example of Django application to export PDF using reportlab and weasyprint

## Main Requirements
Python3
Django
Django REST Framework
Chart.js


## How to use
Create a folder to store this project. Open this folder on terminal and run the following commands

### 1. Clone the project
`git clone https://github.com/rodrigoddc/django_pdf.git`

### 2. Create a virtual environment
`python3 -m venv venv`

### 3. Activate the the virtual environment previously created
on linux: `source ./venv/bin/activate`
on windows: `./venv/Scripts/activate.bat`

### 4. Installing libs
`pip install -r requirements.txt`

### 5. Creating database
`python manage.py makemigrations`

### 6. Migrating database models
`python manage.py migrate`

### 7. Running
`python manage.py runserver`

After that, you'll be able to access the project at 127.0.0.1:8000 or localhost:8000/ on your browser.

##### This application is just a case study, so SECRET_KEY, DEBUG and DATABASES are present as plain text

##### Never do this in production!
Empty file added apps/core/__init__.py
Empty file.
3 changes: 3 additions & 0 deletions apps/core/admin.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
from django.contrib import admin

# Register your models here.
5 changes: 5 additions & 0 deletions apps/core/apps.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
from django.apps import AppConfig


class CoreConfig(AppConfig):
name = 'core'
Empty file.
Empty file added apps/core/models/__init__.py
Empty file.
3 changes: 3 additions & 0 deletions apps/core/models/models.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
from django.db import models

# Create your models here.
6 changes: 6 additions & 0 deletions apps/core/static/core/css/bootstrap.min.css

Large diffs are not rendered by default.

6 changes: 6 additions & 0 deletions apps/core/static/core/js/bootstrap.min.js

Large diffs are not rendered by default.

2 changes: 2 additions & 0 deletions apps/core/static/core/js/jquery.min.js

Large diffs are not rendered by default.

4 changes: 4 additions & 0 deletions apps/core/static/core/js/popper.min.js

Large diffs are not rendered by default.

25 changes: 25 additions & 0 deletions apps/core/templates/core/index.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
{% extends 'base.html' %}
{% load static %}

{% block title %}
<title>Index</title>
{% endblock %}

{% block content %}

<h1 class="h1 my-5">Report Page</h1>

<div class="row">
<div class="container my-4">
<a href="{% url 'core:reportlab_render' %}" class="btn btn-primary">PDF render - Reportlab</a>
<a href="{% url 'core:reportlab_download' %}" class="btn btn-success">PDF Download - Reportlab</a>
</div>
</div>
<div class="row">
<div class="container my-4">
<a href="{% url 'core:weasyprint_render' %}" class="btn btn-primary">PDF render - Weasyprint</a>
<a href="{% url 'core:weasyprint_download' %}" class="btn btn-success">PDF Download - Weasyprint</a>
</div>
</div>

{% endblock %}
19 changes: 19 additions & 0 deletions apps/core/templates/core/weasyprint/base_pdf.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<h1>Report PDF</h1>

<h5>Content from view: </h5>
{% for x in text %}
<p>{{ x }}</p>
{% endfor %}

</body>
</html>
3 changes: 3 additions & 0 deletions apps/core/tests.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
from django.test import TestCase

# Create your tests here.
15 changes: 15 additions & 0 deletions apps/core/urls.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
from django.urls import path

from apps.core.views.view_reportlab import IndexView, PdfRenderView, PdfDownloadView
from apps.core.views.view_weasyprint import PDFRenderView, PDFDownloadView

app_name = 'core'
urlpatterns = [
path('', IndexView.as_view(), name='index'),

path('reportlab-download/', PdfDownloadView.as_view(), name='reportlab_download'),
path('reportlab-render/', PdfRenderView.as_view(), name='reportlab_render'),

path('weasyprint-render/', PDFRenderView.as_view(), name='weasyprint_render'),
path('weasyprint-download/', PDFDownloadView.as_view(), name='weasyprint_download'),
]
Empty file added apps/core/views/__init__.py
Empty file.
53 changes: 53 additions & 0 deletions apps/core/views/view_reportlab.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
import io
from django.http import FileResponse, HttpResponse
from django.views.generic import View, TemplateView

from reportlab.pdfgen import canvas


class IndexView(TemplateView):
template_name = 'core/index.html'


class PdfDownloadView(View):
def get(self, request, *args, **kwargs):

# Create file to recieve data and create the PDF
buffer = io.BytesIO()

# Create the file PDF
pdf = canvas.Canvas(buffer)

# Inserting in PDF where this 2 first arguments are axis X and Y respectvely
pdf.drawString(50, 800, "Some Title")

pdf.showPage()
pdf.save()

# Retrieving the file to start
buffer.seek(0)

# as_attachment=True to make file as an attachment to download
return FileResponse(buffer, as_attachment=True, filename='report.pdf')


class PdfRenderView(View):
def get(self, request, *args, **kwargs):

# Create file to recieve data and create the PDF
buffer = io.BytesIO()

# Create the file PDF
pdf = canvas.Canvas(buffer)

# Inserting in PDF where this 2 first arguments are axis X and Y respectvely
pdf.drawString(50, 800, "Some Title")

pdf.showPage()
pdf.save()

# Retrieving the file to start
buffer.seek(0)

# By default, as_attachment=False
return FileResponse(buffer, filename='report.pdf')
58 changes: 58 additions & 0 deletions apps/core/views/view_weasyprint.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
from django.http import HttpResponse
from django.core.files.storage import FileSystemStorage
from django.template.loader import render_to_string
from django.views.generic import View, TemplateView

from weasyprint import HTML


class PDFRenderView(View):
def get(self, request, *args, **kwargs):
text = [
'Hello',
'World',
'Foo',
'Bar',
]

html_string = render_to_string('core/weasyprint/base_pdf.html', {'text': text})

html = HTML(string=html_string)
html.write_pdf(target='/tmp/report2.pdf')

# Django built-in
fs = FileSystemStorage('/tmp/')

with fs.open('report2.pdf') as pdf:
response = HttpResponse(pdf, content_type='application/pdf')
# inline: make file to be open as to print
response['Content-Disposition'] = 'filename="report2.pdf"'

return response


class PDFDownloadView(View):
def get(self, request, *args, **kwargs):
text = [
'Hello',
'World',
'Foo',
'Bar',
]

html_string = render_to_string('core/weasyprint/base_pdf.html', {'text': text})

html = HTML(string=html_string)
html.write_pdf(target='/tmp/report2.pdf')

# Django built-in
fs = FileSystemStorage('/tmp/')

with fs.open('report2.pdf') as pdf:
response = HttpResponse(pdf, content_type='application/pdf')
# attachment make file content to de downloaded
response['Content-Disposition'] = 'attachment; filename="report2.pdf"'

return response


Empty file added django_pdf/__init__.py
Empty file.
16 changes: 16 additions & 0 deletions django_pdf/asgi.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
"""
ASGI config for django_pdf project.
It exposes the ASGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/3.0/howto/deployment/asgi/
"""

import os

from django.core.asgi import get_asgi_application

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'django_pdf.settings')

application = get_asgi_application()
129 changes: 129 additions & 0 deletions django_pdf/settings.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,129 @@
"""
Django settings for django_pdf project.
Generated by 'django-admin startproject' using Django 3.0.6.
For more information on this file, see
https://docs.djangoproject.com/en/3.0/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/3.0/ref/settings/
"""

import os

# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))


# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/3.0/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'w7zjx++=&ytu2gcc87=!@^40l07fyq#1*$g+dhbdmcsvl2dsf%'

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

ALLOWED_HOSTS = [
'127.0.0.1',
'localhost',
]


# Application definition

INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',

'apps.core',
]

MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

ROOT_URLCONF = 'django_pdf.urls'

TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': ['templates'],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]

WSGI_APPLICATION = 'django_pdf.wsgi.application'


# Database
# https://docs.djangoproject.com/en/3.0/ref/settings/#databases

DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}


# Password validation
# https://docs.djangoproject.com/en/3.0/ref/settings/#auth-password-validators

AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]


# Internationalization
# https://docs.djangoproject.com/en/3.0/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_L10N = True

USE_TZ = True


# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/3.0/howto/static-files/

STATIC_URL = '/static/'
MEDIA_URL = '/media/'

STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
Loading

0 comments on commit 1af052a

Please sign in to comment.