The Wayback Machine - https://web.archive.org/web/20240904065241/https://www.geeksforgeeks.org/how-to-create-pdf-files-in-flask/
Open In App

How to create PDF files in Flask

Last Updated : 29 Sep, 2023
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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.

Screenshot-from-2023-09-19-00-28-03

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.

Screenshot-from-2023-09-19-00-21-49

PDF File Output
Screenshot-from-2023-09-19-00-26-08



Similar Reads

Documenting Flask Endpoint using Flask-Autodoc
Documentation of endpoints is an essential task in web development and being able to apply it in different frameworks is always a utility. This article discusses how endpoints in Flask can be decorated to generate good documentation of them using the Flask-Autodoc module. This module provides the following features - Helps to document endpoints of
4 min read
How to use Flask-Session in Python Flask ?
Flask Session - Flask-Session is an extension for Flask that supports Server-side Session to your application.The Session is the time between the client logs in to the server and logs out of the server.The data that is required to be saved in the Session is stored in a temporary directory on the server.The data in the Session is stored on the top o
4 min read
How to Integrate Flask-Admin and Flask-Login
In order to merge the admin and login pages, we can utilize a short form or any other login method that only requires the username and password. This is known as integrating the admin page and Flask login since it simply redirects users to the admin page when they log in. Let's is how to implement this in this article. Integrate Flask Admin and Fla
8 min read
Minify HTML in Flask using Flask-Minify
Flask offers HTML rendering as output, it is usually desired that the output HTML should be concise and it serves the purpose as well. In this article, we would display minification of output routes of Flask responses using the library - Flask-Minify. Advantages of MinificationWebsites load faster as fewer lines are there to upload and download.Ban
12 min read
Flask URL Helper Function - Flask url_for()
In this article, we are going to learn about the flask url_for() function of the flask URL helper in Python. Flask is a straightforward, speedy, scalable library, used for building, compact web applications. It is a micro framework, that presents developers, useful tools, and, features, for coding REST APIs, and backend data processing, of web apps
11 min read
Upload Multiple files with Flask
In online apps, uploading files is a common task. Simple HTML forms with encryption set to multipart/form information are all that is required to publish a file into a URL when using Flask for file upload. The file is obtained from the request object by the server-side flask script using the request. In this article, we will look at how to upload m
2 min read
Uploading and Downloading Files in Flask
This article will go over how to upload and download files using a Flask database using Python. Basically, we have a section for uploading files where we can upload files that will automatically save in our database. When we upload a file and submit it, a message stating that your file has been uploaded and displaying the file name on the screen ap
7 min read
How to serve static files in Flask
Flask is a lightweight Web Server Gateway Interface or WSGI framework for web applications written in Python. It is designed to make web application development fast and easy and can scale to complex applications. This article describes and demonstrates how to serve various static files in Flask.  Serving Static Files in Flask Let's configure the v
5 min read
Send PDF File through Email using pdf-mail module
pdf_mail module is that library of Python which helps you to send pdf documents through your Gmail account. Installing Library This module does not come built-in with Python. You need to install it externally. To install this module type the below command in the terminal. pip install pdf-mail Function of pdf_mail This module only comes with a singl
2 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 install pikepdftqdm is one of the more comprehensi
2 min read
How to Scrape all PDF files in a Website?
Prerequisites: Implementing Web Scraping in Python with BeautifulSoup Web Scraping is a method of extracting data from the website and use that data for other uses. There are several libraries and modules for doing web scraping in Python. In this article, we'll learn how to scrape the PDF files from the website with the help of beautifulsoup, which
4 min read
Working with PDF files in Python
All of you must be familiar with what PDFs are. In fact, they are one of the most important and widely used digital media. PDF stands for Portable Document Format. It uses .pdf extension. It is used to present and exchange documents reliably, independent of software, hardware, or operating system.Invented by Adobe, PDF is now an open standard maint
8 min read
How to merge multiple excel files into a single files with Python ?
Normally, we're working with Excel files, and we surely have come across a scenario where we need to merge multiple Excel files into one. The traditional method has always been using a VBA code inside excel which does the job but is a multi-step process and is not so easy to understand. Another method is manually copying long Excel files into one w
4 min read
Create a Weather app using Flask | Python
Prerequisite : Flask installation Flask is a lightweight framework written in Python. It is lightweight because it does not require particular tools or libraries and allow rapid web development. today we will create a weather app using flask as a web framework. this weather web app will provide current weather updates of cities searched. Basic setu
2 min read
Flask project - Create a Joke App with PyJokes
Flask is a micro web framework written in Python. It is classified as a micro-framework because it does not require particular tools or libraries. Flask is a lightweight WSGI web application framework. It is designed to make getting started quick and easy, with the ability to scale up to complex applications. For creating joke app we need two libra
2 min read
Create a Real Time Currency Converter app using Flask | Python
Prerequisite: installation of PythonWhat is Flask in Python ? Flask is a popular and lightweight Python web framework, meaning it is a third-party Python library used for developing web applications. Project Setup : create a new directory and name it 'CURRENCY-CONVERTER'. mkdir CURRENCY-CONVERTER &amp;&amp; cd CURRENCY-CONVERTER Inside it create tw
8 min read
Create Postman collection from Flask application using flask2postman
Prerequisite: Introduction to Postman, First App using Flask Since Postman is gaining popularity in the development domain, this article explains a way in which it can be easily integrated with Flask APIs using command-line utility written in Python. We will be using the flask2postman module. But you will be why this module. Here's why - It is a st
3 min read
Create Contact Us using WTForms in Flask
WTForms is a library designed to make the processing of forms easier to manage. It handles the data submitted by the browser very easily. In this article, we will discuss how to create a contact us form using WTForms. Advantages of WT-FORM:We don't have to worry about validators.Avoidance of Cross-Site Request Forgery (CSRF).WTForms come as classes
3 min read
Create GitHub API to fetch user profile image and number of repositories using Python and Flask
GitHub is where developers shape the future of software, together, contribute to the open-source community, manage Git repositories, etc. It is one of the most used tools by a developer and its profile is shared to showcase or let others contribute to its projects. Web Scraping using python is also one of the best methods to get data. In this artic
5 min read
Create a Bar Chart From a DataFrame with Plotly and Flask
Python has a number of powerful open-source libraries that make it an excellent language for Data Analysis and Web Development. One such library is Plotly, which makes it easy to create compelling data visualizations using web technologies. By combining Plotly with Flask, it is possible to create dynamic web pages that update automatically based on
2 min read
How to create charts in bokeh with flask
In this post, we will use the Flask framework to create our web application in Python. The Bokeh library will be used to create interactive bar graphs and we will visualize this graph through a simple frontend HTML page. For this, we will first write the endpoints in Flask which will help us to create Bokeh charts, and then we will create HTML temp
5 min read
Create Scatter Charts in Matplotlib using Flask
In this article, we will see how to create charts in Matplotlib with Flask. We will discuss two different ways how we can create Matplotlib charts in Flask and present it on an HTML webpage with or without saving the plot using Python. File structure Create and Save the Plot in the Static Directory Here, We first created a get_plot() function which
4 min read
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: InstallationWe are using Flask to create CSV output. Please re
3 min read
How to Create a Flask API with MariaDB on AWS EC2
In this article, We are going to create an ec2 instance, install a MySQL database using MariaDB on the ec2 instance, and create an API of Login using the flask python framework. Flask is a micro web framework written in Python. MariaDB is one of the most popular open-source relational database management systems and could be used as a great replace
6 min read
Create Cricket Score API using Web Scraping in Flask
Cricket is one of the famous outdoor sport played worldwide. There are very few APIs providing live scoreboards and none of them are free to use. Using any of the scoreboards available we can create API for ourselves. This method not only works for Cricket Scoreboard but also for any information available online. Following is the flow in which this
6 min read
Python Flask - ImmutableMultiDict
MultiDict is a sub-class of Dictionary that can contain multiple values for the same key, unlike normal Dictionaries. It is used because some form elements have multiple values for the same key and it saves the multiple values of a key in form of a list. Example: C/C++ Code from werkzeug.datastructures import MultiDict orders = MultiDict([(1, 'GFG'
2 min read
Handling 404 Error in Flask
Prerequisite: Creating simple application in Flask A 404 Error is showed whenever a page is not found. Maybe the owner changed its URL and forgot to change the link or maybe they deleted the page itself. Every site needs a Custom Error page to avoid the user to see the default Ugly Error page. GeeksforGeeks also has a customized error page. If we t
4 min read
Python | Using for loop in Flask
Prerequisite: HTML Basics, Python Basics, Flask It is not possible to write front-end course every time user make changes in his/her profile. We use a template and it generates code according to the content. Flask is one of the web development frameworks written in Python. Through flask, a loop can be run in the HTML code using jinja template and a
3 min read
How to Build a Simple Android App with Flask Backend?
Flask is an API of Python that allows us to build up web applications. It was developed by Armin Ronacher. Flask’s framework is more explicit than Django’s framework and is also easier to learn because it has less base code to implement a simple web-Application. A Web-Application Framework or Web Framework is the collection of modules and libraries
8 min read
Subdomain in Flask | Python
Prerequisite: Introduction to Flask In this article, we will learn how to setup subdomains in Flask. But first, let's go through the basic like what is DNS and subdomains. Domain Name System (DNS): The Domain Name System (DNS) is a hierarchical and decentralized naming system for computers, services, or other resources connected to the Internet or
3 min read