Last modified: Jun 01, 2025 By Alexander Williams
Install WeasyPrint in Python: Easy Guide
WeasyPrint is a powerful Python library. It converts HTML documents to PDF. This guide will help you install it easily.
Table Of Contents
Prerequisites for Installing WeasyPrint
Before installing WeasyPrint, ensure you have Python installed. Python 3.6 or higher is recommended.
You also need pip, Python's package manager. Check your Python version with python --version
.
python --version
For Linux users, install system dependencies first. These include Cairo and Pango. Use your package manager.
Installing WeasyPrint Using pip
The easiest way to install WeasyPrint is via pip. Run this command in your terminal.
pip install weasyprint
This will download and install WeasyPrint. It also installs required dependencies.
If you encounter errors, try upgrading pip first. Run pip install --upgrade pip
.
Verifying the Installation
After installation, verify it works. Create a simple Python script to test it.
from weasyprint import HTML
HTML('https://example.com').write_pdf('output.pdf')
This code converts a webpage to PDF. Check for the output.pdf file.
Common Installation Issues
Some users face dependency issues. On Ubuntu/Debian, install these packages first.
sudo apt-get install python3-dev python3-pip python3-cffi libcairo2 libpango-1.0-0 libpangocairo-1.0-0 libgdk-pixbuf2.0-0 libffi-dev shared-mime-info
For macOS, use Homebrew to install dependencies. Run this command.
brew install cairo pango gdk-pixbuf libffi
Windows users may need to install GTK+. Follow the official WeasyPrint documentation.
Using WeasyPrint in Your Projects
WeasyPrint is simple to use. Here's a basic example to convert HTML to PDF.
from weasyprint import HTML
html_content = """
<h1>Hello, WeasyPrint!</h1>
<p>This is a test PDF.</p>
"""
HTML(string=html_content).write_pdf('test.pdf')
This creates a PDF file named test.pdf. It contains your HTML content.
Advanced WeasyPrint Features
WeasyPrint supports CSS styling. You can use external stylesheets.
HTML(string='<h1 style="color: red;">Red Heading</h1>').write_pdf('styled.pdf')
It also handles page breaks and margins. These can be controlled with CSS.
Conclusion
Installing WeasyPrint in Python is straightforward. With this guide, you can convert HTML to PDF easily. For more complex setups, check the official documentation.
If you work with other Python packages, you might find our guides on installing Python packages in Docker or Google Colab helpful.
Happy coding with WeasyPrint!