Build Modern, Print-Ready PDFs with Python, Flask & WeasyPrint - Incentius Blog Home - Incentius - Enable Digital Transformation  

[![Logo](/img_astro/incentius-logo.svg)](/)

Solutions

About

[Case Studies](/portfolio/)

[Blogs](/blog-posts/)

[Career](http://aurochs.freshteam.com/jobs)

Open main menu ![Menu icon](/img_astro/menu1.png)  

[Get In Touch](/contact/)

Solutions

 [![](/img_astro/generative-black.svg) ![](/img_astro/brain-green.svg)

Voice AI](/voice-ai/)

 [![](/img_astro/product-development-black.svg) ![](/img_astro/product-development.svg)

Product Development](/product-engineering/)

 [![](/img_astro/generative-black.svg) ![](/img_astro/brain-green.svg)

Generative AI](/generative-ai/)

 [![](/img_astro/data-black.svg) ![](/img_astro/database-green.svg)

Data Engineering](/data-engineering/)

 [![](/img_astro/mvp-black.svg) ![](/img_astro/rocket-green.svg)

Data & Analytics](/data-analytics/)

 [![](/img_astro/cloud-black.svg) ![](/img_astro/computing-green.svg)

DevOps & CloudOps](/devops-and-cloudops/)

About Us

  [![](/img_astro/product-black.svg)  ![](/img_astro/product-green.svg)

About Us](/about-us/)

  [![](/img_astro/team_black.svg)  ![](/img_astro/team_green.svg)

Team](/team/)

Solutions ![](/img_astro/dropdown-arr.svg) 

[

![](/img_astro/generative-black.svg)

Voice AI



](/voice-ai/)[

![](/img_astro/product-development-black.svg)

Product Development



](/product-engineering/)[

![](/img_astro/generative-black.svg)

Generative AI



](/generative-ai/)[

![](/img_astro/data-black.svg)

Data Engineering



](/data-engineering/)[

![](/img_astro/mvp-black.svg)

Data & Analytics



](/data-analytics/)[

![](/img_astro/cloud-black.svg)

DevOps & CloudOps



](/devops-and-cloudops/)

[Blogs](/blog-posts/) About ![](/img_astro/dropdown-arr.svg) 

[

![](/img_astro/product-black.svg)

About Us



](/about-us/)[

![](/img_astro/team_black.svg)

Team



](/team/)

[Case Studies](/portfolio/) [Career](http://aurochs.freshteam.com/jobs)

[Get In Touch](/contact/)

Build Modern, Print-Ready PDFs with Python, Flask & WeasyPrint

Saurav Jaiswal

1.  Jun 30, 2025
2.  4 min read

![](/_astro/35340343_0731.width-1000_Z1nosTV.webp)

**PDF generation** is a common requirement in modern web applications—especially for reports, invoices, purchase orders, and official documentation. One of the most powerful tools for Python developers is **WeasyPrint**, which allows you to convert **HTML + CSS** into **PDFs** with high-quality rendering.

This blog covers:

*   What is WeasyPrint?  
    
*   Stylish theme ideas for PDFs  
    
*   Flask API implementation  
    
*   Testing the endpoint  
    
*   Tips for customization

## **What is WeasyPrint?**

**WeasyPrint** is a visual rendering engine for HTML and CSS that can output to PDF. It is designed to support modern CSS (like Flexbox, Grid, media queries) and is widely used for document generation.

Think of it as a "headless browser" that prints HTML/CSS to PDF with beautiful accuracy.

### **Why Use WeasyPrint?**

*   Supports modern CSS (Fonts, Flexbox, Grid)  
    
*   Works with templates like Jinja2  
    
*   Clean API and command-line support  
    
*   Supports page breaks, headers/footers, and inline images  
    
*   Ideal for invoices, reports, forms, etc.

### **Step-by-Step Installation Commands**

```

pip install Flask WeasyPrint
For Ubuntu:
sudo apt update
sudo apt install libpango-1.0-0 libpangocairo-1.0-0 libcairo2 libffi-dev shared-mime-info
​​For macOS (using Homebrew):
brew install cairo pango gdk-pixbuf libffi
```

## **Stylish Themes for PDF Design**

To make PDFs not only functional but also beautiful, you can apply CSS themes just like on a webpage. Below are a few example **design themes**:

### **templates/pdf\_template.html**

### **Attractive Modern UI -**

```

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>{{ title }}</title>
  <link rel="stylesheet" href="{{ url_for('static', filename='style.css') }}">
</head>
<body>
  <div class="document">

    <header class="header">
      <div class="logo">
        <h1>{{ heading }}</h1>
        <p>{{ description }}</p>
      </div>
    </header>

    <section class="info-box">
      <h2>Report Summary</h2>
      <p><strong>Date:</strong> {{ date or "June 26, 2025" }}</p>
      <p><strong>Prepared By:</strong> {{ prepared_by or "System Admin" }}</p>
    </section>

    <section class="table-section">
      <h2>Purchase Items</h2>
      <table class="styled-table">
        <thead>
          <tr>
            <th>Item</th>
            <th>Quantity</th>
            <th>Rate (INR)</th>
            <th>Total</th>
          </tr>
        </thead>
        <tbody>
          {% for item in items %}
            <tr>
              <td>{{ item.name }}</td>
              <td>{{ item.qty }}</td>
              <td>{{ item.rate }}</td>
              <td>{{ item.qty * item.rate }}</td>
            </tr>
          {% endfor %}
        </tbody>
      </table>
    </section>

    <footer class="footer">
      <p>Generated by MySystem | &copy; {{ year or "2025" }}</p>
    </footer>

  </div>
</body>
</html>

<style>
body {
  font-family: 'Segoe UI', sans-serif;
  color: #333;
  background: #f7f9fc;
  margin: 0;
  padding: 0;
}

.document {
  padding: 2rem;
  background: white;
  max-width: 800px;
  margin: auto;
  box-shadow: 0 0 20px rgba(0,0,0,0.1);
  border-radius: 10px;
}

.header {
  background-color: #4a90e2;
  color: white;
  padding: 2rem;
  border-radius: 10px 10px 0 0;
  text-align: center;
}

.header h1 {
  margin: 0;
  font-size: 2rem;
}

.info-box {
  background: #eef3f7;
  border-left: 5px solid #4a90e2;
  padding: 1rem 1.5rem;
  margin-top: 1.5rem;
  border-radius: 5px;
}

.info-box h2 {
  margin-top: 0;
  color: #4a4a4a;
}

.table-section {
  margin-top: 2rem;
}

.table-section h2 {
  border-bottom: 2px solid #ddd;
  padding-bottom: 0.5rem;
  margin-bottom: 1rem;
  color: #2c3e50;
}

.styled-table {
  width: 100%;
  border-collapse: collapse;
}

.styled-table thead {
  background-color: #e6f0ff;
  color: #333;
}

.styled-table th,
.styled-table td {
  padding: 12px 15px;
  border: 1px solid #ccc;
}

.styled-table tr:nth-child(even) {
  background-color: #f2f6fc;
}

.footer {
  margin-top: 3rem;
  text-align: center;
  font-size: 0.9rem;
  color: #999;
  border-top: 1px solid #ccc;
  padding-top: 1rem;
}
</style>
```

## **Flask + WeasyPrint PDF Generator API**

Here’s how you can implement a /api/generate-pdf endpoint using Flask and WeasyPrint.

### **Folder Structure**

```

project/
 │
├── app.py
├── templates/
 │   └── pdf_template.html


app.py

from flask import Flask, request, render_template, send_file, url_for
from weasyprint import HTML
import tempfile
import os

app = Flask(__name__)

@app.route("/api/generate-pdf", methods=["POST"])
def generate_pdf():
    data = request.json

    # Render HTML with data
    rendered_html = render_template("pdf_template.html",
                                    title=data.get("title", "PDF Document"),
                                    heading=data.get("heading", "PDF Generated"),
                                    description=data.get("description", ""),
                                    items=data.get("items", []))

    # Generate temporary file path
    with tempfile.NamedTemporaryFile(delete=False, suffix=".pdf") as tmp:
        pdf_path = tmp.name

    # Generate PDF
    HTML(string=rendered_html, base_url=request.base_url).write_pdf(pdf_path)

    return send_file(pdf_path, as_attachment=True, download_name="document.pdf")
```

**Example Request (Postman or JS/Fetch)**

```

POST /api/generate-pdf
Content-Type: application/json

{
    "title": "Monthly Purchase Report",
    "heading": "Report - June 2025",
    "description": "This report contains the list of purchases for the month of June.",
    "items": [
        { "name": "Laptop", "qty": 2, "rate": 55000 },
        { "name": "Keyboard", "qty": 5, "rate": 1200 }
    ]
}
```

## **Tips for Better PDF Styling**

*   Use **Google Fonts** with @import in your CSS  
    
*   Include company **logos** or QR codes with <img> tags and relative paths  
    
*   Use **media queries** (@media print) to hide or show certain elements  
    
*   Add **page numbers** using @page and counter(page)  
    
*   For better print quality, always use **high-resolution images**

```

@page {
    size: A4;
    margin: 1in;
}
```

## **Common Issues & Solutions**

*   **Images not showing**  
    **Solution:** Use base\_url when rendering HTML (e.g., with WeasyPrint or Flask renderers)
*   **CSS not applied**  
    **Solution:** Use url\_for('static', filename='path/to/file.css') in templates
*   **Broken fonts**  
    **Solution:** Use system fonts (like Arial, Times) or host fonts locally (avoid external CDNs)
*   **Header/Footer not repeating on every page**  
    **Solution:** Use position: running(header) in CSS and define headers/footers using @page rules

## **Conclusion**

With **WeasyPrint** and **Flask**, you can create stylish, responsive, and professional PDF documents just like a web page. Thanks to its HTML + CSS-based design, your frontend team can collaborate with backend developers to make the perfect document experience.

![](/_astro/unnamed_1.width-1000_ueH2P.webp)

About Author

![](/_astro/Saurav_Jaiswal.width-300_Zw9n5Q.webp)

Saurav Jaiswal

![](/img_astro/thumb.png)

### See What Our Clients Say

![](/img_astro/left-chevron_1.svg)

![](/img_astro/left-chevron_2.svg)

![](/img_astro/mind-gap-crop.svg)

Mindgap

Incentius has been a fantastic partner for us. Their strong expertise in technology helped deliver some complex solutions for our customers within challenging timelines. Specific call out to Sujeet and his team who developed custom sales analytics dashboards in SFDC for a SoCal based healthcare diagnostics client of ours. Their professionalism, expertise, and flexibility to adjust to client needs were greatly appreciated. MindGap is excited to continue to work with Incentius and add value to our customers.

Samik Banerjee

Founder & CEO

![](/img_astro/trusted-by-businesses/worldatwork_coloured.webp)

World at Work

Having worked so closely for half a year on our website project, I wanted to thank Incentius for all your fantastic work and efforts that helped us deliver a truly valuable experience to our WorldatWork members. I am in awe of the skills, passion, patience, and above all, the ownership that you brought to this project every day! I do not say this lightly, but we would not have been able to deliver a flawless product, but for you. I am sure you'll help many organizations and projects as your skills and professionalism are truly amazing.

Shantanu Bayaskar

Senior Project Manager

![](/img_astro/trusted-by-businesses/gogla_coloured.webp)

Gogla

It was a pleasure working with Incentius to build a data collection platform for the off-grid solar sector in India. It is rare to find a team with a combination of good understanding of business as well as great technological know-how. Incentius team has this perfect combination, especially their technical expertise is much appreciated. We had a fantastic time working with their expert team, especially with Amit.

Viraj gada

Gogla

![](/img_astro/trusted-by-businesses/humblex_coloured.webp)

Humblx

Choosing Incentius to work with is one of the decisions we are extremely happy with. It's been a pleasure working with their team. They have been tremendously helpful and efficient through the intense development cycle that we went through recently. The team at Incentius is truly agile and open to a discussion in regards to making tweaks and adding features that may add value to the overall solution. We found them willing to go the extra mile for us and it felt like working with someone who rooted for us to win.

Samir Dayal Singh

CEO Humblx

![](/img_astro/mind-gap-crop.svg)

Transportation & Logistics Consulting Organization

Incentius is very flexible and accommodating to our specific needs as an organization. In a world where approaches and strategies are constantly changing, it is invaluable to have an outsourcer who is able to adjust quickly to shifts in the business environment.

Transportation & Logistics Consulting Organization

Consultant

![](</img_astro/trusted-by-businesses/Mudraksh & McShaw.png>)

Mudraksh & McShaw

Incentius was instrumental in bringing the visualization aspect into our investment and trading business. They helped us organize our trading algorithms processing framework, review our backtests and analyze results in an efficient, visual manner.

Priyank Dutt Dwivedi

Mudraksh & McShaw Advisory

![](/img_astro/mind-gap-crop.svg)

Leading Healthcare Consulting Organization

The Incentius resource was highly motivated and developed a complex forecasting model with minimal supervision. He was thorough with quality checks and kept on top of multiple changes.

Leading Healthcare Consulting Organization

Sr. Principal

![](/img_astro/mind-gap-crop.svg)

US Fortune 100 Telecommunications Company

The Incentius resource was highly motivated and developed a complex forecasting model with minimal supervision. He was thorough with quality checks and kept on top of multiple changes.

Incentive Compensation

Sr. Director

Most Read

[

![](/_astro/ChatGPT_Image_Apr_2_2025_12_06_35_PM.width-1000_ZUChn3.webp)

Optimizing Large-Scale Data Exports: FastAPI, GraphQL, and AWS S3

Struggling with slow, inefficient file downloads in your application? Generating and handling large file downloads can be a nightmare—UI freezing, server overload, and endless waiting.

![](/_astro/Vinay_Chaudhari.width-300_1QPJnB.webp)

Vinay Chaudhari

1.  Apr 08, 2025
2.  4 min read









](/blog-posts/optimizing-large-scale-data-exports-fastapi-graphql-and-aws-s3/)[

![](/_astro/Screenshot_2025-04-02_at_12.09.33_PM.width-1000_ZyU6y1.webp)

How to Build a Web Search Agent with Phidata: A Step-by-Step Guide

Phidata is an **open-source framework** for building AI agents with capabilities like memory, tool use, and reasoning​ It’s model-agnostic and supports various large language models (LLMs), allowing developers to turn any LLM (like OpenAI GPT or local models) into a functional **search agent**.

![](/_astro/Kartik_Puri.width-300_1YNCyp.webp)

Kartik Puri

1.  Apr 02, 2025
2.  4 min read









](/blog-posts/how-to-build-a-web-search-agent-with-phidata-a-step-by-step-guide/)[

![](/_astro/e20f5335-cbf6-414c-a096-7d2849109cff.width-1000_15DfBS.webp)

Migrating to Soketi: Improving Our Real- Time Communication Architecture

Our journey with real-time data communication has evolved significantly. Initially using

Flask-SocketIO with Vue, we faced several challenges that led us to seek a more robust

solution.

![](/_astro/pratik.width-300_Z2vB9eu.webp)

Pratik Patel

1.  Mar 17, 2025
2.  4 min read









](/blog-posts/migrating-to-soketi-improving-our-real-time-communication-architecture/)[

![](/_astro/startup-employee-looking-business-charts-usin.width-1000_2knrAp.webp)

Understanding AI Agents: A Comprehensive Guide to AI Agentic Workflows

In the rapidly evolving landscape of artificial intelligence, AI Agents have emerged as a transformative technology that represents far more than just industry jargon.

![](/_astro/chetan_piucv.width-300_ZK3Vor.webp)

Chetan Patel

1.  Feb 28, 2025
2.  4 min read









](/blog-posts/understanding-ai-agents-a-comprehensive-guide-to-ai-agentic-workflows/)

## We use cookies

We use cookies to improve site. Some cookies are necessary for our website and services to function properly. Other cookies are optional and help personalize your experience, including advertising and analytics.You can consent to all cookies or decline all optional cookies. Without a selection, our default cookie settings will apply.

I agree I decline

[![logo](/img_astro/logo.svg)](/)

Incentius is a technology and professional services company providing analytics, operations and product engineering services.

 [![facebook](/img_astro/facebook.svg)](https://www.facebook.com/Incentius/)[![twitter](/img_astro/twitter.svg) ](https://x.com/incentius/)[![linkedin](/img_astro/linkedin.svg)](https://www.linkedin.com/company/incentius/posts/?feedView=all)

![location](/img_astro/pin.svg)

Office No.201B, 2nd Floor, Beta-1, Giga Space IT Park, Viman Nagar, Pune - 411014, Maharashtra, India

![email](/img_astro/message-icon.svg)

info@incentius.com

![phone](/img_astro/telephone.svg)

+1 (302) 415 3208

![](/img_astro/secure-footer.svg) ![](/img_astro/secure-footer-mobile.svg)

*   Solutions
*   [Voice AI](/voice-ai/)
*   [Generative AI](/generative-ai/)
*   [Data Engineering](/data-engineering/)
*   [Product Development](/product-engineering/)
*   [Data & Analytics](/data-analytics/)
*   [DevOps & CloudOps](/devops-and-cloudops/)
*   [UI/UX Design](/ui-ux-design/)

*   Recent Blog
*   [Medallion Architecture in Practice: Six Layers, One Source of Truth](/blog-posts/medallion-architecture-in-practice-six-layers-one-source-of-truth/)
*   ["Document later" is how teams say "document never"](/blog-posts/document-later-is-how-teams-say-document-never/)
*   [Your Business & AI - What It Actually Means for You](/blog-posts/your-business-ai-what-it-actually-means-for-you/)
*   [How Internal Agent-Built Software Reduced Our SaaS Dependency](/blog-posts/how-internal-agent-built-software-reduced-our-saas-dependency/)
*   [MarkItDown: A Powerful Utility for File Conversion to Markdown](/blog-posts/markitdown-a-powerful-utility-for-file-conversion-to-markdown/)
*   [Python 3.14: A Game-Changing Release for Modern Development](/blog-posts/python-314-a-game-changing-release-for-modern-development/)
*   [Building a RESTful Blog API with Flask and Swagger: A Complete Guide to Streamlined API Development](/blog-posts/building-a-restful-blog-api-with-flask-and-swagger-a-complete-guide-to-streamlined-api-development/)
*   [Tailwind CSS 4.0 vs 3.x: What Changed and How We Implemented It](/blog-posts/tailwind-css-40-vs-3x-what-changed-and-how-we-implemented-it/)
*   [The Future of AI: What to Expect in the Next 5 Years](/blog-posts/the-future-of-ai-what-to-expect-in-the-next-5-years/)

*   Menu
*   [About](/about-us/)
*   [Blog](/blog-posts/)
*   [Career](http://aurochs.freshteam.com/jobs)
*   [Case Studies](/portfolio/)
*   [For Startups](/startups/)
*   [Let's Talk](/contact/)

© Copyright 2025 Incentius

[Request Site](/)  
  
[Terms and Conditions](/)  
  
[Privacy Policy](/privacy-policy/)