What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Generate the PDF in three stages: render a Django template to HTML, load that HTML in a headless Chromium page with Pyppeteer, and return the bytes in a normal Django HttpResponse. Use application/pdf and Content-Disposition so clients download the result. DRF’s Response is intended for data processed by renderers; Django’s response classes are the straightforward choice once page.pdf() has already produced PDF bytes (DRF responses; Django request and response objects).

Request-to-PDF flow

  1. Authenticate and validate the DRF request.
  2. Build the context from your database or request data.
  3. Render a dedicated Django template.
  4. Launch Chromium, load the rendered markup, and await page.pdf().
  5. Close the page and browser in a finally block.
  6. Return the resulting bytes as a Django HttpResponse.

This example uses an API view and accepts a customer ID. Adapt authentication, permissions, validation, and data access to your application.

Install Pyppeteer and plan Chromium availability

The project README states that Pyppeteer requires Python 3.8 or newer. On first use it can download Chromium when a suitable executable is not available; you can also run pyppeteer-install. In production, deliberately choose how the browser is installed, pin the library and browser combination you deploy, and verify required operating-system libraries in your image or host (Pyppeteer project README).

python -m pip install pyppeteer

For a repeatable container build, install the package during image creation and run the browser installation step there rather than making the first API request download a browser. Set an explicit executable path with executablePath when your image provides Chromium or Chrome.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
#1 Best Overall
PDF Extra 2024| Complete PDF Reader and Editor | Create, Edit, Convert, Combine, Comment, Fill & Sign PDFs | Lifetime License | 1 Windows PC | 1 User [PC Online code]
  • EDIT text, images & designs in PDF documents. ORGANIZE PDFs. Convert PDFs to Word, Excel & ePub.
  • READ and Comment PDFs – Intuitive reading modes & document commenting and mark up.
  • CREATE, COMBINE, SCAN and COMPRESS PDFs
  • FILL forms & Digitally Sign PDFs. PROTECT and Encrypt PDFs
  • LIFETIME License for 1 Windows PC or Laptop. 5GB MobiDrive Cloud Storage Included.

Create a print-oriented Django template

Put a template such as templates/invoices/invoice.html in your normal Django template directory. Keep styles self-contained or make every external URL reachable by the Chromium process. Print CSS is the default for PDF generation, so use @media print for page-specific rules.

<!doctype html>
<html>
<head>
  <meta charset="utf-8">
  <title>Invoice {{ invoice.number }}</title>
  <style>
    @page { size: A4; margin: 18mm 15mm 20mm; }
    body { font-family: Arial, sans-serif; color: #222; }
    h1 { margin: 0 0 12px; }
    table { width: 100%; border-collapse: collapse; }
    th, td { border-bottom: 1px solid #ddd; padding: 7px; text-align: left; }
    .total { text-align: right; font-weight: 700; }
    .avoid-break { break-inside: avoid; }
    @media print { .screen-only { display: none; } }
  </style>
</head>
<body>
  <h1>Invoice {{ invoice.number }}</h1>
  <p>{{ invoice.customer_name }}</p>
  <table>
    <thead><tr><th>Description</th><th>Amount</th></tr></thead>
    <tbody>
      {% for line in invoice.lines %}
      <tr class="avoid-break"><td>{{ line.description }}</td><td>{{ line.amount }}</td></tr>
      {% endfor %}
    </tbody>
  </table>
  <p class="total">Total: {{ invoice.total }}</p>
</body>
</html>

Django auto-escaping protects ordinary variable output. Do not mark untrusted request content as safe HTML. If the template references images, fonts, or styles, use absolute, authenticated URLs that the browser can access, or inline assets you control.

Implement the DRF endpoint

The following synchronous APIView renders the template, loads it with a data: URL, and returns a downloadable PDF. Loading the rendered document as a data URL avoids exposing a temporary HTML file. The exact loading approach is an implementation choice; Pyppeteer’s API provides the browser and page primitives.

from django.http import HttpResponse
from django.template.loader import render_to_string
from rest_framework.views import APIView
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from rest_framework import status
from pyppeteer import launch

from .models import Invoice

class InvoicePdfView(APIView):
    permission_classes = [IsAuthenticated]

    async def get(self, request, invoice_id):
        try:
            invoice = Invoice.objects.prefetch_related("lines").get(
                id=invoice_id, owner=request.user
            )
        except Invoice.DoesNotExist:
            return Response({"detail": "Not found."}, status=status.HTTP_404_NOT_FOUND)

        html = render_to_string("invoices/invoice.html", {"invoice": invoice})
        browser = None
        try:
            browser = await launch(
                headless=True,
                args=["--no-sandbox", "--disable-setuid-sandbox"],
                # executablePath="/usr/bin/chromium",  # set in your image if needed
            )
            page = await browser.newPage()
            await page.setContent(html, waitUntil="networkidle0")
            pdf_bytes = await page.pdf({
                "format": "A4",
                "printBackground": True,
                "margin": {
                    "top": "18mm", "right": "15mm",
                    "bottom": "20mm", "left": "15mm",
                },
                "preferCSSPageSize": True,
            })
        finally:
            if browser is not None:
                await browser.close()

        response = HttpResponse(pdf_bytes, content_type="application/pdf")
        response["Content-Disposition"] = (
            f'attachment; filename="invoice-{invoice.id}.pdf"'
        )
        return response

Use an async server path that supports your deployment, or isolate the blocking browser work in a worker when your stack is synchronous. Do not return a DRF Response containing raw PDF bytes unless you have intentionally configured a renderer for that representation; a regular Django response is clearer for already-rendered bytes.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Rank #2
MobiPDF Lifetime - Professional PDF Editor for Windows | Edit, Sign & Convert PDFs | Best Adobe Acrobat Pro Alternative | Lifetime License
  • Edit PDFs with Ease. Modify text, images, and layouts directly within your PDF documents.
  • Convert & Organize. Export PDFs to Word, Excel, or ePub, and organize files with ease.
  • Read & Annotate. Enjoy intuitive reading modes and powerful tools to comment, highlight, and mark up PDFs.
  • Create & Manage PDFs. Create new PDFs, combine multiple files, scan documents, and compress for easy sharing.
  • Fill & Sign Forms. Complete forms and digitally sign documents with secure e-signature tools.

Choose PDF options deliberately

Pyppeteer’s Page.pdf() supports paper format or explicit dimensions, margins, orientation, page ranges, background printing, and header/footer templates (Pyppeteer API reference).

Requirement Setting or technique
Paper format: "A4", or custom width/height.
Margins margin object with CSS lengths such as mm or in.
Landscape landscape: true.
Background colors/images printBackground: true.
Selected pages pageRanges: "1-3" or another supported range.
Header/footer displayHeaderFooter: true plus HTML templates and reserved margins.
CSS page rules preferCSSPageSize: true when @page should control size.

PDF rendering uses print media by default. If your design is written for screen media, call await page.emulateMedia("screen") before pdf(); otherwise your @media print rules and print defaults apply. For dynamic pages, wait for a selector, a known delay, or network idle before generating the file. With a data URL and inline markup, ensure fonts and images have finished loading before capture.

Headers, authentication, and data safety

  • Apply DRF authentication and object-level authorization before querying the invoice. Never rely on an ID alone.
  • Validate any user-controlled filename and keep it to a safe, predictable value.
  • Do not pass secrets into template markup or browser-visible URLs. If the browser must fetch protected assets, use short-lived, scoped URLs or controlled request headers.
  • Limit document size, page count, and request frequency. Chromium processes consume substantial memory and may outlive a timed-out HTTP request if cleanup is missing.
  • Use a per-request browser for simple, low-volume endpoints. For higher throughput, a carefully managed browser pool can reduce startup work, but impose concurrency limits and recycle unhealthy processes.

Deployment, latency, and reliability

PDF creation starts a browser operation and is slower than serializing JSON. Set an application timeout that exceeds your page and browser timeouts, and return a useful server error when Chromium cannot start. In a worker-based architecture, enqueue a job and let the client poll for a completed file when documents are large or numerous.

Log request ID, document ID, browser launch failures, navigation timeouts, and PDF duration without logging private document contents. Keep Chromium dependencies in the same image tested in staging. Close pages and browsers in all exception paths, and monitor process count and memory. These are operational safeguards, not measured performance guarantees.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Rank #3
Adobe Acrobat Pro | PDF Software | Convert, Edit, E-Sign, Protect | PC/Mac Online Code | Activation Required
  • Create and edit PDFs. Collaborate with ease. E-sign documents and collect signatures. Get everything done in one app, wherever you go.
  • Edit text and images without jumping to another app.
  • E-sign documents or request e-signatures on any device. Recipients don’t need to log in to e-sign.
  • Convert PDFs to editable Microsoft Word, Excel, or PowerPoint documents.
  • Share PDFs for collaboration. Commenting features make it easy for reviewers to comment, mark up, and annotate.

Troubleshooting common failures

Chromium executable not found

Install the browser during deployment, run pyppeteer-install, or provide the correct executablePath. Confirm the service user can execute it.

Browser fails to start in a container

Install the operating-system libraries required by your Chromium build. Some restricted environments require sandbox configuration; only use --no-sandbox when you understand the isolation trade-off and have compensated with container or host security.

Blank or incomplete PDF

Check that the template renders valid HTML, that asset URLs are reachable from the server, and that you wait for the required selector or network activity. Inline critical CSS and images when external resources are unreliable.

Styles look different from the website

PDF uses print media by default. Add print rules, enable printBackground, or call emulateMedia("screen") before pdf() if screen styling is intentional.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Rank #4
PDF Extra Lifetime - Professional PDF Editor - Best Adobe Acrobat Pro Alternative - Lifetime License for Windows PC
  • Perfect Adobe Acrobat Pro alternative – lifetime license for Windows 10 and 11.
  • EDIT text, images, pages, hyperlinks, designs in PDF documents. ORGANIZE PDFs.
  • READ and Comment on PDFs – Intuitive reading modes & document commenting and mark up tools!
  • CREATE, COMBINE, SCAN and COMPRESS PDFs.
  • FILL forms & Digitally Sign PDFs. Work with Digital certificates

Images or fonts are missing

Use absolute URLs, verify DNS and authentication from the server environment, wait for loading, and check browser logs. A local filesystem path in HTML is not automatically available to Chromium.

Requests time out

Reduce page complexity, remove unnecessary third-party resources, set explicit navigation and application timeouts, and move long documents to an asynchronous worker. Always close the browser after cancellation or failure.

Download opens inline instead of prompting

Set Content-Disposition to attachment; filename="...pdf". Django documents as_attachment=True as the mechanism that sets this header when using a file response (Django response documentation).

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Maintenance warning: Pyppeteer versus its recommended alternative

The Pyppeteer repository currently says: “Attention: this repo is unmaintained and has been outside of minor changes for a long time. Please consider playwright-python as an alternative.” That is a maintenance warning from the project itself, not evidence of a performance comparison. If a new project is not constrained to Pyppeteer’s API, evaluate playwright-python; if you must use Pyppeteer, pin versions, test Chromium upgrades, and budget time for compatibility fixes (Pyppeteer repository README).

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Best Value
PDF Pro 3 - PDF editor to create, edit, convert and merge PDFs - 100% Compatible with Adobe Acrobat - for Windows 11, 10, 8.1, 7
  • ALL-IN-ONE SOLUTION – read, edit, convert, merge and protect your PDF files
  • MAXIMUM FUNCIONALITY – create interactive forms, compare PDFs, bates numbering, find and replace text or colors, convert documents, OCR engine, comment, highlight, fill out and print forms, document protection and others
  • EASY TO INSTALL AND USE – well-structured user-interface, in-program instructions, free tech support whenever you need it
  • GREAT VALUE FOR MONEY - why spend a fortune if you can have maximum functionality at a reasonable price - this also fits the requirements of companies very well

Or skip the browser setup

If your requirement is simply to turn a URL into a PDF or image, ScreenshotNeo provides a website screenshot API and MCP server. It accepts consent banners before capture and removes more than 60 known consent platforms, newsletter popups, and chat widgets; each step can be disabled. Bot checks, CAPTCHAs, blank pages, timeouts, failed loads, and cache hits are not billed, and response headers identify the page verdict and billing status. Its MCP server provides take_screenshot, get_page_info, and capture_pdf tools for Claude, Cursor, and other MCP clients.

For a PDF, call the API with the target URL and PDF options described in the ScreenshotNeo documentation. The same endpoint also supports full-page images, CSS-selector element capture, device presets, custom JavaScript and CSS, cookies and headers, waits, blocking rules, signed links, asynchronous webhooks, bulk capture, caching, and usage reporting.

curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp
import requests
r = requests.get("https://api.screenshotneo.com/v1/shot", params={"access_key": "YOUR_API_KEY", "url": "https://stripe.com"}, timeout=90)
open("shot.webp", "wb").write(r.content)
const q = new URLSearchParams({ access_key: 'YOUR_API_KEY', url: 'https://stripe.com' });
const res = await fetch(`https://api.screenshotneo.com/v1/shot?${q}`);

The Free plan includes 1,000 screenshots per month with no card; paid plans start at $5 for 3,000 shots. Create a free ScreenshotNeo account.

Frequently Asked Questions

Can I return a PDF from a DRF function view?

Yes. Render the template, await Pyppeteer’s PDF bytes, and return a Django HttpResponse from the function decorated with DRF’s api_view, applying the same authentication and validation decisions.

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Is a data URL required when loading rendered HTML?

No. It is a convenient choice for self-contained markup. You can instead serve a protected temporary URL or navigate to an application page, provided the browser can access every required asset.

Why does my PDF have an extra blank page?

Inspect CSS page size, margins, fixed-height containers, and forced page breaks. Conflicting @page dimensions and content wider than the printable area are common causes.

Quick Recap

Bestseller No. 1
PDF Extra 2024| Complete PDF Reader and Editor | Create, Edit, Convert, Combine, Comment, Fill & Sign PDFs | Lifetime License | 1 Windows PC | 1 User [PC Online code]
PDF Extra 2024| Complete PDF Reader and Editor | Create, Edit, Convert, Combine, Comment, Fill & Sign PDFs | Lifetime License | 1 Windows PC | 1 User [PC Online code]
READ and Comment PDFs – Intuitive reading modes & document commenting and mark up.; CREATE, COMBINE, SCAN and COMPRESS PDFs
$99.99
Bestseller No. 2
MobiPDF Lifetime - Professional PDF Editor for Windows | Edit, Sign & Convert PDFs | Best Adobe Acrobat Pro Alternative | Lifetime License
MobiPDF Lifetime - Professional PDF Editor for Windows | Edit, Sign & Convert PDFs | Best Adobe Acrobat Pro Alternative | Lifetime License
Edit PDFs with Ease. Modify text, images, and layouts directly within your PDF documents.; Convert & Organize. Export PDFs to Word, Excel, or ePub, and organize files with ease.
$99.99
Bestseller No. 3
Adobe Acrobat Pro | PDF Software | Convert, Edit, E-Sign, Protect | PC/Mac Online Code | Activation Required
Adobe Acrobat Pro | PDF Software | Convert, Edit, E-Sign, Protect | PC/Mac Online Code | Activation Required
Edit text and images without jumping to another app.; Convert PDFs to editable Microsoft Word, Excel, or PowerPoint documents.
$239.88
Bestseller No. 4
PDF Extra Lifetime - Professional PDF Editor - Best Adobe Acrobat Pro Alternative - Lifetime License for Windows PC
PDF Extra Lifetime - Professional PDF Editor - Best Adobe Acrobat Pro Alternative - Lifetime License for Windows PC
Perfect Adobe Acrobat Pro alternative – lifetime license for Windows 10 and 11.; EDIT text, images, pages, hyperlinks, designs in PDF documents. ORGANIZE PDFs.
$99.99
Bestseller No. 5
PDF Pro 3 - PDF editor to create, edit, convert and merge PDFs - 100% Compatible with Adobe Acrobat - for Windows 11, 10, 8.1, 7
PDF Pro 3 - PDF editor to create, edit, convert and merge PDFs - 100% Compatible with Adobe Acrobat - for Windows 11, 10, 8.1, 7
ALL-IN-ONE SOLUTION – read, edit, convert, merge and protect your PDF files
$29.99

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.