How to create PDF files in Flask
Last Updated :
29 Sep, 2023
Whether it's generating a report, exporting data, or creating catalogs, Python and the Flask web framework provide powerful tools to accomplish this task. In this article, we'll explore how to generate both PDF files using Python and Flask.
Creating PDF files in Flask
Step 1: Installation
We are using Flask to create CSV output. Please refer:- Install Flask and Install Python for proper installation.
Step 2: Create a Virtual Environment
In this step, we will first create a virtual environment for our project. Please refer to create virtual environment for further information.
Step 3: Create Folders
Now, we will create a folder in the given format in the given picture below. We will create a static folder, and a templates folder, and inside the templates folder, create an index.html file. We will also create an app.py file where we will write our Python code.

Step 4: Write HTML Code
In this step, we will create a file index.html and paste this code inside that file. In this code, we have created an HTML form, and when a person the book details. It is saved inside a pdf file.
HTML
<!-- templates/index.html -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Generate PDF</title>
</head>
<body>
<h1>Generate and Download PDF</h1>
<form method="POST" action="/generate-pdf">
<label for="title">Title:</label>
<input type="text" id="title" name="title" required><br>
<label for="author">Author:</label>
<input type="text" id="author" name="author" required><br>
<label for="publication_year">Publication Year:</label>
<input type="number" id="publication_year" name="publication_year" required><br>
<input type="submit" value="Add Book">
</form>
<p><a href="/generate-pdf" download>Download Book Catalog (PDF)</a></p>
</body>
</html>
Step 5: Write Python Code
In this step, we will write our Flask logic in the form of Python code.
Import All Required Libraries: Import all required libraries and module like Flask, render_template, request, Response, send_file and other as shown in the code itself.
Python3
from flask import Flask, render_template, request, Response, send_file
from io import BytesIO
from reportlab.pdfgen import canvas
app = Flask(__name__)
# Initialize an empty list to store user input data
user_data = []
Function for Default Route: In this function, when a user visits the root URL of the web application, Flask will execute the index() function, which, in turn, renders the 'index.html' template and sends the resulting HTML page as the response to the user's web browser. Code implementation is given below in index() function.
Python3
# home page
@app.route('/')
def index():
return render_template('index.html')
Function to Take Input Data from User: This function code handles requests to '/generate-pdf', allows users to submit form data to collect book information, generates a PDF catalog from that data, and provides the PDF for download. Code is given below in generate_pdf() function.
Python3
@app.route('/generate-pdf', methods=['GET', 'POST'])
def generate_pdf():
if request.method == 'POST':
# Retrieve user input from the form
title = request.form.get('title')
author = request.form.get('author')
publication_year = request.form.get('publication_year')
# Validate and store the user input
if title and author and publication_year:
user_data.append({
'title': title,
'author': author,
'publication_year': publication_year
})
pdf_file = generate_pdf_file()
return send_file(pdf_file, as_attachment=True, download_name='book_catalog.pdf')
Function to Genrate PDF: This function code defines a function to create a PDF catalog of books using the ReportLab library and sets up a web application (presumably for serving this catalog). Code implementation is given below inside generate_pdf_file() function.
Python3
def generate_pdf_file():
buffer = BytesIO()
p = canvas.Canvas(buffer)
# Create a PDF document
p.drawString(100, 750, "Book Catalog")
y = 700
for book in user_data:
p.drawString(100, y, f"Title: {book['title']}")
p.drawString(100, y - 20, f"Author: {book['author']}")
p.drawString(100, y - 40, f"Year: {book['publication_year']}")
y -= 60
p.showPage()
p.save()
buffer.seek(0)
return buffer
if __name__ == '__main__':
app.run(debug=True)
Full Implementation of app.py file Python code
Python3
from flask import Flask, render_template, request, Response, send_file
from io import BytesIO
from reportlab.pdfgen import canvas
app = Flask(__name__)
# Initialize an empty list to store user input data
user_data = []
@app.route('/')
def index():
return render_template('index.html')
@app.route('/generate-pdf', methods=['GET', 'POST'])
def generate_pdf():
if request.method == 'POST':
# Retrieve user input from the form
title = request.form.get('title')
author = request.form.get('author')
publication_year = request.form.get('publication_year')
# Validate and store the user input
if title and author and publication_year:
user_data.append({
'title': title,
'author': author,
'publication_year': publication_year
})
pdf_file = generate_pdf_file()
return send_file(pdf_file, as_attachment=True, download_name='book_catalog.pdf')
def generate_pdf_file():
buffer = BytesIO()
p = canvas.Canvas(buffer)
# Create a PDF document
p.drawString(100, 750, "Book Catalog")
y = 700
for book in user_data:
p.drawString(100, y, f"Title: {book['title']}")
p.drawString(100, y - 20, f"Author: {book['author']}")
p.drawString(100, y - 40, f"Year: {book['publication_year']}")
y -= 60
p.showPage()
p.save()
buffer.seek(0)
return buffer
if __name__ == '__main__':
app.run(debug=True)
Step 6: Run the File
In this step, just run the file and you will see this form. Just fill this form and a click on Add Book button. Data will be added and then click on Download Book Catalog button to download the file in PDF format.

PDF File Output

Similar Reads
How to create CSV output in Flask?
In this article, we will see how to create a CSV output using Flask. Python and Flask Web Frameworks provide powerful tools to generate a report, export data and create catalogs. We will see how to generate both CSV files using Python and Flask. Creating CSV files in Python FlaskStep 1: Installation
3 min read
How to Crack PDF Files in Python?
Prerequisite: tqdm In this article, we will learn How to Crack a Protected PDF File Using Python. Here we will use the Brute force Method, to Crack a PDF File using pikepdf module in Python. Required Modules : pikepdf is a Python module, which is used to create, manipulate, and repair PDF Files.pip
2 min read
How to Upload File in Python-Flask
File uploading is a typical task in web apps. Taking care of file upload in Flask is simple all we need is to have an HTML form with the encryption set to multipart/form information to publish the file into the URL. The server-side flask script brings the file from the request object utilizing the r
2 min read
How to serve static files in Flask
In Flask, static files refer to files such as CSS, JavaScript, images, videos, and audio files that do not change dynamically. Flask provides a built-in way to serve these static files using the /static directory. This guide will show how to serve different types of static files in a Flask web appli
4 min read
How to Change Port in Flask app
In this article, we will learn to change the port of a Flask application. The default port for the Flask application is 5000. So we can access our application at the below URL. http://127.0.0.1:5000/ We may want to change the port may be because the default port is already occupied. To do that we ju
1 min read
How to Use CSS in Python Flask
Flask is a popular web framework for Python that makes it easy to build web applications. One of the key elements of any web application is styling, which is where CSS (Cascading Style Sheets) comes in. CSS allows us to control the look and feel of our web pages, making them more attractive and user
3 min read
How to Install Flask-CORS in Python
In this article, we will learn to install Flask-CORS which is a Python module and a Flask extension that supports and allows cross-origin resource sharing (CORS) through a simple decorator. Due to security concerns, cross-domain cookie submission is disabled by default. We will look at how to instal
3 min read
How to Run a Flask Application
After successfully creating a Flask app, we can run it on the development server using the Flask CLI or by running the Python script. Simply execute one of the following commands in the terminal: flask --app app_name runpython app_nameFile StructureHere, we are using the following folder and file. D
4 min read
Upload and Read Excel File in Flask
In this article, we will look at how to read an Excel file in Flask. We will use the Python Pandas library to parse this excel data as HTML to make our job easier. Pandas additionally depend on openpyxl library to process Excel file formats. Before we begin, make sure that you have installed both Fl
3 min read
Delete pages from a PDF file in Python
In this article, We are going to learn how to delete pages from a pdf file in Python programming language. Introduction Modifying documents is a common task performed by many users. We can perform this task easily with Python libraries/modules that allow the language to process almost any file, the
4 min read