PrecisionPDF in Python

Use the precisionpdf package to generate PDFs from Python. The HTML interface accepts a document file or an HTML string and writes a PDF to a path or returns its bytes.

Install

Create and activate a virtual environment:

python3 -m venv .venv
. .venv/bin/activate
python -m pip install precisionpdf

On Windows, activate the environment with .venv\Scripts\Activate.ps1 in PowerShell. Install into the environment that runs your application.

Render a file

Use the HTML document from the getting-started guide, then save this as render.py:

from precisionpdf import HTML

HTML(filename="document.html").write_pdf("document.pdf")

Run python render.py, then open document.pdf. Relative images, fonts, and stylesheets are resolved from the input file’s location.

Render an HTML string

Pass generated markup with string. Set base_url when the markup uses relative resources:

from pathlib import Path
from precisionpdf import HTML

assets = Path("assets").resolve().as_uri() + "/"
html = """<html lang="en">
<head><title>Report</title></head>
<body><h1>Report</h1><img src="logo.png" alt="Company"></body>
</html>"""
HTML(string=html, base_url=assets).write_pdf("report.pdf")

Generate dynamic content with your application’s template engine before conversion. The renderer does not execute JavaScript in the document.

Get PDF bytes

Omit the destination to receive PDF bytes:

from precisionpdf import HTML

pdf = HTML(string="<h1>Hello, PDF.</h1>").write_pdf()
with open("hello.pdf", "wb") as output:
    output.write(pdf)

Use the bytes in an HTTP response or store them through your application’s storage layer.

Set page layout and fonts

Put page dimensions, margins, and document typography in CSS:

@page { size: A4; margin: 18mm; }
@font-face {
  font-family: Report;
  src: url("fonts/report.woff2");
}
body { font-family: Report, serif; }

Package the referenced font with the document and keep its relative path consistent in production.

Handle failures

Loading, asset fetching, rendering, and writing can raise errors. Handle them at the request or job boundary and avoid returning a partial or failed document as a successful result.

Check the privacy overview for document and diagnostic-log handling.