Top 10 Python PDF generator libraries: Complete guide for developers (2025)

Table of contents

    This guide compares 10 Python PDF libraries across five criteria: license model, HTML/CSS rendering, performance on large documents, API design, and community support. Find the right library for your project, from basic PDF generation to full document workflows.
    Top 10 Python PDF generator libraries: Complete guide for developers (2025)
    Python PDF library: Which one?

    10 Python PDF libraries for different use cases:

    How to generate PDF in Python

    PDF is the standard format for documents across industries. A Python PDF library lets you:

    • Generate reports and invoices — Create invoices, statements, and reports without manual layout
    • Build document workflows — Fillable forms, digital signatures, merge/split files
    • Convert HTML to PDF — Turn web templates into print-ready brochures and ebooks
    • Archive images — Bundle scans and photos into searchable PDFs
    • Add PDF endpoints — Serve PDF generation from web apps or serverless functions

    Python has many PDF libraries — from lightweight, dependency-free tools to HTML-to-PDF engines and commercial APIs. The sections below compare 10 Python PDF libraries across five criteria to help you choose.

    1. Nutrient API

    Nutrient DWS API generates, customizes, and processes PDFs at scale. It handles form filling, signatures, annotations, OCR, and merging via a cloud REST API — no local rendering engines required.

    Key features

    • HTML to PDF — CSS, custom fonts, headers/footers, and page numbers
    • Document conversion — Convert Office files (Word, Excel, PowerPoint), images, and Markdown to PDF
    • PDF operations — Form filling, digital signatures, annotations, watermarking, OCR, merging, compression, and redaction
    • Accessibility — PDF/UA auto-tagging for accessible documents
    • Platform-agnostic — Call from Python, JavaScript, or any HTTP client
    • SOC 2 Type 2 and GDPR compliant — Documents processed in memory, never stored

    Getting started

    1. Sign up — Visit the Nutrient website(opens in a new tab) and sign up for an account.
    2. Request an API key — After signing up, obtain an API key from the dashboard.
    3. Pricing — Credit-based. Free trial available.

    Example: Generate a PDF from HTML

    import requests
    import json
    # Define the HTML part of the document.
    instructions = {
    'parts': [
    {
    'html': 'index.html'
    }
    ]
    }
    # Send the request to the Nutrient API.
    response = requests.request(
    'POST',
    'https://api.nutrient.io/build',
    headers={
    'Authorization': 'Bearer {YOUR_API_KEY}' # Replace with your API key.
    },
    files={
    'index.html': open('index.html', 'rb'),
    },
    data={
    'instructions': json.dumps(instructions)
    },
    stream=True
    )
    # Save the resulting PDF.
    if response.ok:
    with open('result.pdf', 'wb') as fd:
    for chunk in response.iter_content(chunk_size=8096):
    fd.write(chunk)
    else:
    print(response.text)
    exit()

    To generate a PDF, the instructions dictionary specifies that the PDF should be generated from the index.html file. The code then sends a POST request to the Nutrient API with the HTML content. The API processes this data and returns a PDF file. If the request is successful, the PDF is saved as result.pdf. If there’s an error, the response is printed for troubleshooting.

    Generated PDF using Nutrient API

    Advanced usage

    • Dynamic content — Combine with data sources to generate invoices, reports, or certificates
    • Other Nutrient services — Use with annotation, form filling, or OCR
    • Batch processing — Handle large-scale PDF generation

    Why use Nutrient API

    • 30+ PDF toolsConversion, watermarking, OCR, form processing, digital signatures, compression, and redaction in one API
    • Credit-based pricing — Form filling costs 1 credit, OCR costs 3 credits, digital signatures cost 10 credits. Combine multiple operations in a single request
    • Python client — Official async Python client with type hints, available via pip install nutrient-dws
    • Rate limit — 100 requests per minute per API key

    Sign up for a free account(opens in a new tab) to test the API.

    Official Python client for Nutrient Processor API

    Nutrient offers an official Python client(opens in a new tab), available via pip install nutrient-dws. It requires Python 3.10+.

    The client provides:

    • Direct methodsmerge_pdfs, ocr_pdf, watermark_pdf, compress_pdf, extract_text
    • Builder pattern — Chain multiple operations: add parts → apply actions → set output → execute
    • Input flexibility — File paths, bytes, file-like objects, and remote URLs
    • Async and type-safe — Full type hints with async/await support
    • Error handling — Specific exceptions for validation, API, authentication, and network errors

    The Python client doesn’t expose HTML-to-PDF generation directly. Use requests to call the /build endpoint for HTML conversion. Then use the client for further processing.

    2. FPDF Python: Create PDF with pure Python

    FPDF(opens in a new tab) is a lightweight, dependency-free library for building PDFs from scratch.

    Key features

    • Quick text and image insertion — Add paragraphs, pictures, and simple lines.
    • Multipage support — Loop through pages with just a few commands.
    • Basic formatting — Set fonts, colors, and alignments easily.
    • Fast and small — No dependencies, works in minimal environments.

    Best for: Simple multipage documents, or image-rich flyers that only need basic text, images, and custom formatting.

    Installation

    Install FPDF using pip:

    Terminal window
    pip install fpdf

    Usage example

    Create a PDF with FPDF:

    from fpdf import FPDF
    # Create an instance of an FPDF class.
    pdf = FPDF()
    # Add a page.
    pdf.add_page()
    # Set the font.
    pdf.set_font("Arial", size=12)
    # Add a cell.
    pdf.cell(200, 10, txt="Hello, this is a PDF generated using FPDF!", ln=True, align='C')
    # Save the PDF with the name `.pdf`.
    pdf.output("output.pdf")
    print("PDF generated successfully!")

    In this example, you created a PDF document, added a single page, and inserted a line of centered text. The PDF was saved to output.pdf.

    Advanced example: Generating a multipage PDF with images and custom formatting

    In this example, you’ll create a Python script to generate a multipage PDF that includes both text and images. You’ll use the fpdf library to:

    • Add multiple pages to the PDF.
    • Insert custom text on each page.
    • Include an image (e.g. example.jpg) on each page.

    Ensure you have an image file (e.g. example.jpg) you want to include in the PDF. Place this image in the same directory as your script.

    Save the following Python code in a .py file (e.g. generate_pdf.py):

    from fpdf import FPDF
    # Create an instance of an FPDF class.
    pdf = FPDF()
    # Add multiple pages.
    for i in range(3):
    pdf.add_page() # Add a new page.
    pdf.set_font("Arial", size=16) # Set the font for text.
    pdf.cell(200, 10, txt=f"Page {i+1}", ln=True, align='C') # Add text to the page.
    pdf.image("example.jpg", x=10, y=30, w=100) # Add an image to the page.
    # Output the PDF to a file.
    pdf.output("multi_page.pdf")
    print("Multipage PDF with images generated successfully!")

    Open your terminal, navigate to the folder where the script and image are stored, and run:

    Terminal window
    python generate_pdf.py

    This will generate a multi_page.pdf file in the same directory. Each page will have custom text and the example.jpg image placed at specified coordinates.

    0:00
    0:00
    Ready to get started?

    Try Nutrient API for free and generate PDFs in minutes.

    3. Generating PDFs with ReportLab

    ReportLab(opens in a new tab) is an open source library for creating PDFs with text, images, charts, and graphics.

    Key features

    • PDF generation — Text, images, charts, and custom graphics
    • Advanced graphics — Lines, shapes, curves, and illustrations
    • Document templates — Consistent layout across documents
    • Custom fonts and styles — Full control over fonts, colors, and styles

    Best for: Complex layouts with charts, graphics, and custom typography — reports, brochures, or invoices.

    Licensing

    ReportLab has a free community edition under the ReportLab Open Source License. A commercial edition is available with additional features and support.

    Installation

    To install ReportLab, use pip:

    Terminal window
    pip install reportlab

    Alternatively, if you’re using a system like Anaconda, you can install it via conda:

    Terminal window
    conda install -c conda-forge reportlab

    Usage example

    Generate a PDF with ReportLab:

    from reportlab.lib.pagesizes import letter
    from reportlab.pdfgen import canvas
    # Create a PDF file.
    c = canvas.Canvas("example.pdf", pagesize=letter)
    # Draw some text.
    c.drawString(100, 750, "Hello, this is a PDF generated with ReportLab!")
    # Save the PDF.
    c.save()

    In this example, a PDF file named example.pdf is created with a simple line of text.

    More advanced features

    ReportLab offers more advanced features, outlined below.

    Adding graphics

    You can draw more than just text — for example, lines, shapes, and even custom images:

    from reportlab.lib.pagesizes import letter
    from reportlab.pdfgen import canvas
    c = canvas.Canvas("example_graphics.pdf", pagesize=letter)
    # Draw a line.
    c.line(50, 700, 550, 700)
    # Draw a rectangle.
    c.rect(50, 600, 200, 100)
    # Draw an image.
    c.drawImage("example_image.jpg", 300, 500, width=100, height=100)
    c.save()

    Generated PDF using ReportLab

    Creating charts

    You can also generate various types of charts using ReportLab’s rlbcharts module. It allows you to create bar charts, line charts, and pie charts with extensive customization.

    ReportLab works well for detailed reports with charts, graphs, and complex page layouts. For simpler PDFs, consider FPDF or img2pdf.

    4. Generating PDFs with PDFKit

    PDFKit(opens in a new tab) is a thin Python wrapper around wkhtmltopdf(opens in a new tab), letting you generate pixel-perfect PDFs directly from HTML/CSS.

    Key features

    • Full HTML/CSS ↔︎ PDF conversion — Supports media queries, page breaks, and inline JavaScript execution.
    • Complex layout handling — Preserves grids, tables, and layered elements without extra tweaking.
    • Drop-in integration — Call one function (pdfkit.from_file/string/url) and deploy on any system that has wkhtmltopdf installed.

    Best for: Converting webpages or HTML templates into styled PDFs — perfect for reports, ebooks, and other web-native documents.

    Installation

    To use PDFKit, install both the pdfkit library and the wkhtmltopdf tool. Follow the steps below to set it up.

    1. Install the PDFKit library:

      Terminal window
      pip install pdfkit
    2. Download and install wkhtmltopdf from its official website(opens in a new tab), or use a package manager:

      • macOS (Homebrew):

        Terminal window
        brew install wkhtmltopdf
      • Ubuntu/Debian:

        Terminal window
        sudo apt-get install wkhtmltopdf
      • Windows: Download the installer from the official website(opens in a new tab) and follow the installation instructions.

    Converting HTML to PDF

    Here’s a simple guide for converting an HTML file into a PDF:

    import pdfkit
    # Specify the path to your HTML file.
    html_file = 'example.html'
    # Define the output PDF file name.
    output_pdf = 'output.pdf'
    # Convert HTML to PDF.
    pdfkit.from_file(html_file, output_pdf)

    To learn more about converting HTML to PDF using Python, check out our blog post:

    5. Generating PDFs with WeasyPrint

    WeasyPrint(opens in a new tab) is a Python library that turns modern HTML + CSS into print-ready PDFs while faithfully preserving the source layout and styles.

    Key features

    • Accurate HTML/CSS rendering — Handles flexbox, grid, media queries, and other modern web layouts.
    • Rich styling support — Full CSS3, responsive design, and custom fonts.
    • Unicode and multilingual — Reliable output for RTL and non-Latin scripts.
    • SVG embedding — Renders inline or linked SVG graphics without rasterization.

    Best for: Web content conversion, styled reports, invoices, receipts, and ebooks from HTML + CSS.

    Installation

    Install WeasyPrint via pip:

    Terminal window
    pip install weasyprint

    WeasyPrint requires system dependencies. On Ubuntu/Debian:

    Terminal window
    sudo apt-get install libffi-dev libpq-dev

    Usage example

    Generate a styled PDF with WeasyPrint:

    from weasyprint import HTML
    # Define HTML content.
    html_content = '''
    <!DOCTYPE html>
    <html>
    <head>
    <title>Sample PDF</title>
    <style>
    body { font-family: Arial, sans-serif; }
    h1 { color: #333; }
    </style>
    </head>
    <body>
    <h1>Hello, this is a PDF generated using WeasyPrint!</h1>
    <p>This PDF is created from HTML content with CSS styling.</p>
    </body>
    </html>
    '''
    # Convert HTML to PDF.
    HTML(string=html_content).write_pdf("output.pdf")
    print("PDF generated successfully!")

    In this example, HTML(string=html_content).write_pdf("output.pdf") converts the provided HTML content into a PDF file named output.pdf.

    To learn more about WeasyPrint, visit our blog post on how to generate PDF from HTML using Python.

    6. Generating PDFs with borb

    borb(opens in a new tab) is a modern, pure-Python library for both creating and manipulating PDFs.

    It has high-level layout primitives (Paragraph, Table, Chart) and low-level drawing commands.

    Key features

    • Rich layout engine — Paragraphs, images, tables, barcodes, SVG, pie and bar charts.
    • Interactive elements — Forms, annotations, document outlines.
    • Post-processing — Merge, split, redact, encrypt existing PDFs.

    Best for: Complex pages (tables, charts, barcodes) and PDF manipulation (merge, split, encrypt) with no external binaries.

    Installing borb

    borb can be installed via pip:

    Terminal window
    pip install borb

    Usage example

    from borb.pdf import Document, Page, PDF, SingleColumnLayout, Paragraph
    # 1. Create the document and a page.
    doc = Document()
    page = Page()
    doc.add_page(page)
    # 2. Choose a layout manager for that page.
    layout = SingleColumnLayout(page)
    # 3. Add content via the layout.
    layout.add(Paragraph("Hello, borb!"))
    # 4. Serialize to a PDF file.
    with open("borb_hello.pdf", "wb") as fh:
    PDF.dumps(fh, doc)

    7. Generating PDFs with img2pdf

    img2pdf(opens in a new tab) is a tiny utility for stitching images into a single, lossless PDF.

    Key features

    • Any image ↔︎ PDF — Handles JPEG, PNG, TIFF, and more.
    • Batch combine — Merge dozens of images into one document in file order.
    • Lossless output — Keeps original pixels; no reencoding artefacts.
    • Fast and minimal — Pure Python, no heavy dependencies.

    Best for: Bundling images — such as scans, photos, and graphics — into a single, lossless PDF when you don’t need additional text or formatting.

    Installation

    Install via pip:

    Terminal window
    pip install img2pdf

    Usage example

    Convert images to PDF:

    import img2pdf
    # List of image file paths.
    image_files = ['image1.jpg', 'image2.png', 'image3.tiff']
    # Convert images to PDF.
    with open('output.pdf', 'wb') as f:
    f.write(img2pdf.convert(image_files))
    print("PDF generated successfully!")

    In this example, img2pdf.convert() takes a list of image file paths and writes them into a PDF file named output.pdf.

    Ready to get started?

    Try Nutrient API for free and generate PDFs in minutes.

    8. Using Pillow with img2pdf

    Pillow(opens in a new tab) lets you resize, crop, rotate, and convert images before passing them to img2pdf.

    Key features

    • Image editing — Resize, crop, rotate, filter, or watermark images
    • Format conversion — Convert TIFF, BMP, or RAW to JPEG/PNG
    • Works with img2pdf — Pass processed images to img2pdf.convert(...)

    Best for: Preprocessing images before converting to PDF.

    Installation

    Install both libraries:

    Terminal window
    pip install Pillow img2pdf

    Code examples

    Example 1: Preprocess and convert a single image

    from PIL import Image
    import img2pdf
    # Open an image using Pillow.
    image = Image.open('input.jpg')
    # Resize the image (optional).
    image = image.resize((800, 600))
    # Convert the image to another format if needed (optional).
    image = image.convert('RGB')
    # Save the modified image temporarily.
    image.save('modified_image.jpg')
    # Convert the modified image to PDF.
    with open('output.pdf', 'wb') as f:
    f.write(img2pdf.convert('modified_image.jpg'))
    print("PDF generated successfully!")

    Example 2: Preprocess and combine multiple images

    from PIL import Image
    import img2pdf
    # List of image file paths.
    image_files = ['image1.jpg', 'image2.png', 'image3.tiff']
    # Preprocess images.
    processed_images = []
    for image_file in image_files:
    image = Image.open(image_file)
    image = image.resize((800, 600)) # Resize image (optional).
    image = image.convert('RGB') # Convert format (optional).
    processed_image_path = f'processed_{image_file}'
    image.save(processed_image_path)
    processed_images.append(processed_image_path)
    # Convert preprocessed images to PDF.
    with open('output.pdf', 'wb') as f:
    f.write(img2pdf.convert(processed_images))
    print("PDF generated successfully!")

    9. Generating PDFs with xhtml2pdf

    xhtml2pdf(opens in a new tab) converts HTML + CSS to PDF with a single function call.

    Best for: Styled invoices, browser-ready reports, marketing flyers, or offline documents generated straight from web templates.

    Key features

    • Layout-faithful HTML → PDF — Preserves CSS, page breaks, and headers and footers.
    • Embedded assets — Packs fonts and images so the PDF matches the original design.
    • Multipage and complex structures — Handles tables, floats, and long documents with ease.

    Installation

    To use xhtml2pdf, you can install it via pip:

    Terminal window
    pip install xhtml2pdf

    Usage example

    Here’s a simple example of how to convert an HTML file to a PDF using xhtml2pdf:

    from xhtml2pdf import pisa
    # Define a function to convert HTML to PDF.
    def convert_html_to_pdf(source_html, output_filename):
    # Open output file for writing (binary mode).
    with open(output_filename, "wb") as output_file:
    # Convert HTML to PDF.
    pisa_status = pisa.CreatePDF(source_html, dest=output_file)
    # Return `true` if the conversion was successful.
    return pisa_status.err == 0
    # HTML content to be converted.
    html_content = """
    <!DOCTYPE html>
    <html lang="en">
    <head>
    <meta charset="UTF-8">
    <title>Sample PDF</title>
    <style>
    h1 { color: #2E86C1; }
    p { font-size: 14px; }
    </style>
    </head>
    <body>
    <h1>Hello, PDF!</h1>
    <p>This is a PDF generated from HTML using xhtml2pdf.</p>
    </body>
    </html>
    """
    # Convert HTML to PDF.
    if convert_html_to_pdf(html_content, "output.pdf"):
    print("PDF generated successfully!")
    else:
    print("PDF generation failed!")

    In this example, xhtml2pdf is used to convert a simple HTML string into a PDF file named output.pdf. The library handles the HTML structure and CSS styling, enabling you to produce a well-formatted PDF.

    10. Generating PDFs with pdfdocument

    pdfdocument(opens in a new tab) is a minimal Python library for creating basic PDFs with minimal setup. Its intuitive API makes it ideal for simple documents like reports, memos, or letters — without the overhead of more complex libraries.

    Key features

    • Straightforward API — Quickly add headings, paragraphs, and images.
    • Lightweight and dependency-free — Good for small projects or scripting.
    • Customizable layout — Basic support for formatting, heading levels, and visual structure.

    Best for: Simple text-based documents and quick PDF output where you don’t need advanced layout engines.

    Installation

    You can install pdfdocument via pip:

    Terminal window
    pip install pdfdocument

    Usage example

    Here’s a simple example of how to use pdfdocument to generate a PDF:

    from pdfdocument.document import PDFDocument
    # Create a PDF document.
    pdf = PDFDocument("output.pdf")
    # Start the PDF.
    pdf.init_report()
    # Add a title and some text.
    pdf.h1("Hello, PDFDocument!")
    pdf.p("This is a PDF generated using the pdfdocument library.")
    # Add an image (optional).
    # pdf.image("path_to_image.jpg", width=200)
    # Finalize and save the PDF.
    pdf.generate()
    print("PDF generated successfully!")

    In this example, pdfdocument is used to create a PDF file named output.pdf. The code adds a title and a paragraph of text, demonstrating how easily you can generate a basic PDF. The generate() method finalizes and saves the document.

    Comparison: Which Python PDF generator is right for you?

    PDF generatorEase of useFunctionalityPerformanceCommunity supportLicense
    Nutrient APIHighExcellentExcellentProfessionalCommercial
    borbModerateHighHighGrowingAGPL
    xhtml2pdfEasyModerateModerateHighApache
    Pillow + img2pdfEasyModerateHighHighMIT-CMU / GNU LGPL
    img2pdfEasyLowHighLowGNU LGPL
    WeasyPrintModerateHighModerateHighBSD 3-Clause
    PDFKitModerateHighModerateHighMIT
    ReportLabModerateHighModerateHighBSD / Commercial
    FPDFEasyLowHighModerateMIT
    pdfdocumentEasyLowHighLowBSD

    Recommendations

    • Nutrient API — For production apps needing forms, signatures, annotations, OCR, and support
    • xhtml2pdf — Simple HTML-to-PDF with good community support
    • Pillow with img2pdf — Image preprocessing before PDF conversion
    • img2pdf — Fast image-to-PDF conversion
    • WeasyPrint and PDFKit — HTML/CSS rendering with good community support
    • ReportLab — Custom graphics and charts
    • FPDF and pdfdocument — Basic PDFs with minimal dependencies

    Quick guide:

    • Simple PDF generation → FPDF or img2pdf
    • HTML/CSS conversion → WeasyPrint or PDFKit
    • Complex layouts → ReportLab
    • Production apps → Nutrient API

    Common issues while generating PDFs in Python

    1. Handling large documents

    • Problem: Generating large PDFs with many pages, images, or complex content can lead to high memory consumption and slow processing times.
    • Solutions and best practices:
      • Incremental PDF writing — Instead of generating an entire document in memory, write pages to disk incrementally with streaming options using libraries like reportlab.
      • Optimize image sizes — Compress and resize images before adding them to the PDF to reduce memory usage.
      • Chunk processing — Divide content generation into smaller chunks and process them sequentially to avoid memory overload.

    Example:

    pdf = FPDF()
    for _ in range(1000): # Instead of loading all pages at once, process incrementally.
    pdf.add_page()
    pdf.cell(200, 10, txt="Chunk processing example", ln=True)
    pdf.output("large_output.pdf")

    This example generates 1,000 pages, processing each one incrementally without loading all pages at once, improving memory usage.

    2. Managing memory usage

    • Problem: Memory leaks or excessive memory consumption when processing multiple PDF files or handling large datasets.
    • Solutions and best practices:
      • Use generators — Leverage Python generators to process data lazily instead of loading everything into memory at once.
      • Garbage collection — Explicitly clear unused objects using gc.collect() after processing large chunks of data.
      • Use streaming APIs — Libraries like pdfkit support streaming outputs instead of storing content in memory.

    Example:

    import gc
    from fpdf import FPDF
    pdf = FPDF()
    pdf.add_page()
    pdf.set_font("Arial", size=12)
    pdf.cell(200, 10, "Memory management example", ln=True)
    pdf.output("output.pdf")
    # Clear memory.
    del pdf
    gc.collect()

    This example creates a PDF and then it explicitly clears the memory by deleting the object and invoking garbage collection to optimize memory usage.

    3. Ensuring cross-platform compatibility

    • Problem: PDF output may look different on various operating systems due to font availability or encoding issues.
    • Solutions and best practices:
      • Embed fonts — Use built-in font embedding features in libraries like FPDF or reportlab to ensure consistency across platforms.
      • Use standard fonts — Stick to common fonts like Helvetica, Times, and Courier to avoid OS-specific font dependencies.
      • Encoding handling — Always specify text encoding (e.g. UTF-8) to avoid compatibility issues when generating multilingual PDFs.

    Example:

    pdf.set_font("Arial", size=12, style='B') # Use cross-platform fonts.
    pdf.set_auto_page_break(auto=True, margin=15)

    This example uses a built-in font (Arial) and sets page breaks, ensuring compatibility across different systems with consistent font handling.

    4. Optimizing performance

    • Problem: PDF generation can be slow, especially with large datasets, high-resolution images, or complex formatting.
    • Solutions and best practices:
      • Minimize draw calls — Reduce the number of drawing operations by batching similar elements together.
      • Use cached resources — Cache repeated elements (e.g. logos, headers) to avoid redundant processing.
      • Asynchronous processing — Use asynchronous processing for high-performance document generation in web applications.

    Example:

    from concurrent.futures import ThreadPoolExecutor
    def generate_pdf_chunk(data):
    pdf = FPDF()
    pdf.add_page()
    pdf.set_font("Arial", size=12)
    pdf.cell(200, 10, txt=data, ln=True)
    pdf.output(f"chunk_{data}.pdf")
    with ThreadPoolExecutor() as executor:
    executor.map(generate_pdf_chunk, ["Page 1", "Page 2", "Page 3"])

    This example demonstrates parallel PDF generation with a thread pool, allowing chunks of data to be processed simultaneously, improving overall speed.

    5. Maintaining layout consistency

    • Problem: Inconsistent layout issues arise when adding dynamic content such as tables, charts, or paragraphs.
    • Solutions and best practices:
      • Define layout templates — Use a consistent document template to standardize layout across all generated PDFs.
      • Auto-adjust layout — Use libraries that support automatic content fitting and page breaks, such as reportlab.
      • Test different screen sizes — Check the final PDF layout on different devices to ensure consistency.

    Example:

    pdf.set_auto_page_break(auto=True, margin=10)
    pdf.multi_cell(0, 10, "This is a long paragraph that will wrap automatically.")

    This example uses multi_cell to handle long paragraphs automatically, ensuring text wraps properly without breaking the layout.

    By following these solutions and best practices, developers can efficiently generate PDFs in Python while overcoming common challenges related to performance, compatibility, and security.

    Conclusion

    This guide covered 10 Python PDF libraries — from lightweight tools like FPDF and img2pdf to commercial options like Nutrient API.

    Choose based on your needs:

    • Simple PDFs — FPDF or img2pdf
    • HTML conversion — WeasyPrint or PDFKit
    • Production apps — Nutrient API for forms, signatures, and support

    Start your free trial(opens in a new tab) to get 200 API credits.

    FAQ

    Which Python PDF library should I use for simple PDFs?

    FPDF is a lightweight library for generating simple PDFs with text, images, and basic formatting. It requires no external dependencies.

    Can I generate PDFs with embedded images using Python?

    Yes. You can generate PDFs with embedded images using libraries like ReportLab, WeasyPrint, and img2pdf. Each of these libraries provides support for adding images to your PDFs, with img2pdf being specifically designed for converting images to PDFs.

    What role does Pillow play when integrated with img2pdf?

    Pillow preprocesses images (resize, crop, convert formats) before passing them to img2pdf for PDF conversion.

    What features does Nutrient API offer for generating PDFs in Python?

    Nutrient API supports HTML-to-PDF conversion, fillable forms, document merging, watermarks, annotations, OCR, and digital signatures. It has an official Python client library.

    What features does PDFKit offer for converting HTML to PDF?

    PDFKit wraps wkhtmltopdf to convert HTML documents into PDFs with CSS styling and JavaScript execution.

    Hulya Masharipov

    Hulya Masharipov

    Technical Writer

    Hulya is a frontend web developer and technical writer who enjoys creating responsive, scalable, and maintainable web experiences. She’s passionate about open source, web accessibility, cybersecurity privacy, and blockchain.

    Explore related topics

    Try for free Ready to get started?