PyLaTeX Report
Build technical PDF reports from Python using pandas or Polars DataFrames, Matplotlib figures, and native TikZ / PGFPlots graphs. The project wraps PyLaTeX with helpers for repeated experiments, figure mosaics, and reusable report styles.
Getting started
You need Python 3.10 or newer and a TeX installation to generate PDFs.
Install the Python library
Once the first PyPI release is published, install into your Python environment with pip:
python -m pip install pylatex-report
Or add it to an existing uv project:
uv add pylatex-report
Or install the current GitHub version (requires Git):
python -m pip install "git+https://github.com/HaroldGueneau/pylatex-report.git"
With uv, use uv add "git+https://github.com/HaroldGueneau/pylatex-report.git" instead. The installed distribution is named pylatex-report; its Python import is from pylatex_report import LatexReport. Python imports use underscores instead of hyphens.
Install TeX separately
pip and uv install the Python dependencies, but do not install TeX. You need pdflatex on your PATH and the LaTeX packages used by the report; TikZ graphs also need tikz and pgfplots. If latexmk is available, the library uses it to manage compilation passes.
On macOS, install MacTeX. On Ubuntu, the following packages match the test workflow:
sudo apt-get update
sudo apt-get install -y latexmk lmodern texlive-latex-extra texlive-pictures
Generate a first report
Save this as quickstart.py in any writable directory. It uses the installed library and needs no files from this repository.
import pandas as pd
from matplotlib.figure import Figure
from pylatex_report import LatexReport
scores = pd.DataFrame({"Model": ["Baseline", "Candidate"], "Score": [0.81, 0.86]})
chart = Figure(figsize=(5, 2.5), layout="constrained")
ax = chart.subplots()
ax.bar(scores["Model"], scores["Score"])
ax.set_ylabel("Score")
report = LatexReport(
"quickstart",
"Model comparison",
"Research team",
table_of_contents=False,
separate_cover=False,
)
report.add_section("Results")
report.add_text("Evaluation scores on the held-out dataset.")
report.add_table(scores, "Model scores", precision=2)
report.add_plot(chart, "Scores by model")
pdf = report.generate_report("reports")
print(pdf)
Run it with python quickstart.py, or uv run python quickstart.py from your uv project. It writes reports/quickstart.pdf beneath the current directory.
Examples
The examples directory contains two runnable reports. Their scripts and data live in the repository and are not installed with the library.
| Example | What it demonstrates | Sample output |
|---|---|---|
| ML experiment | Compare three classifiers across five seeds. Reuse pandas summaries for a mean ± standard deviation table, TikZ curves with error bars, and grouped bars. Keep per-seed Matplotlib diagnostics in a paginated mosaic. | |
| Fund risk report | Read daily returns from CSV. Use Polars for performance and risk tables, a TikZ histogram of losses, and an empirical distribution in steps. Include branded pages and Matplotlib diagnostics. |
To run them, clone the repository and install its locked development and example dependencies with uv:
git clone https://github.com/HaroldGueneau/pylatex-report.git
cd pylatex-report
uv sync --locked
uv run --locked python -B -m examples.ml_experiment --output-dir reports
uv run --locked python -B -m examples.fund_risk \
--input examples/data/fund_returns.csv \
--as-of 2025-12-30 \
--output-dir reports
The linked sample PDFs were generated with these commands, using --output-dir output/pdf. The fund example writes reports/fund_risk.pdf with the commands above. Its bundled CSV contains simulated returns through December 31, 2025. The command above includes observations through December 30. Omit --input to use the bundled CSV or omit --as-of to report through the latest observation.
To use your own CSV, provide date,return columns with one row per date. The script sorts the rows by date. Dates use YYYY-MM-DD. Returns are daily simple returns in decimal form, so 0.0125 means 1.25%. Each return must be finite and greater than -1, and at least two observations must fall on or before the cutoff. When the cutoff falls between observations, the report shows the requested date and the period through the last included observation.
Run the fund report with Docker
From the project root, build the image once and create the output directory on the host.
docker build -f examples/Dockerfile.fund-risk -t fund-risk .
mkdir -p reports
docker run --rm --network none \
--user "$(id -u):$(id -g)" \
--mount "type=bind,source=$PWD/examples/data/fund_returns.csv,target=/returns.csv,readonly" \
--mount "type=bind,source=$PWD/reports,target=/output" \
fund-risk --input /returns.csv --as-of 2025-12-30 --output-dir /output
Docker mounts the CSV read-only. The report writes reports/fund_risk.pdf as the sole output file. For a scheduled job, reuse the image and pass the current CSV path and cutoff date. Runs using the same output directory replace the previous PDF.
Usage guide
Tables and repeated runs
add_table(df, title, precision=2)accepts pandas and Polars DataFrames. Useinclude_indexto control whether row labels are shown andlongtable=Truefor a multipage table with repeated headers.add_aggregate_table(runs, "Scores by model", keys="Model", metrics=["Score"])renders mean ± standard deviation. Each run is a pandas or Polars DataFrame with the same unique model keys. Usehighlight="max"orhighlight="min"to bold the highest or lowest mean in each row.LatexReport.aggregate_tables(runs, keys="Model", metrics=["Score"])returns the means and standard deviations as two pandas DataFrames. The defaultddof=1computes sample standard deviations. Missing observations are skipped per cell. Without explicit keys, rows are aligned by pandas index or Polars row position.
Both table methods accept formats and column_headers, keyed by the original data column labels.
report.add_table(
metrics,
"Fund performance",
formats={"Annual return": ".2%", "Sharpe": ".2f"},
column_headers={"Annual return": "Annual\nreturn"},
)
Formats use Python's format specifiers. For example, .2% displays 0.0744 as 7.44%. Columns without a format still use precision. In an aggregate table, the same format is applied to the mean and standard deviation, and highlighting uses the unrounded means. Use \n in a column label or its display header to start a new line. The fund report and ML experiment show both options in use.
Figure mosaics
add_plot accepts one Matplotlib Figure or an iterable of figures. For example, the following call lays out up to six panels per page.
report.add_plot(figures, "Diagnostics", columns=3, rows_per_page=2, panel_labels=True)
When the mosaic spans multiple pages, each group gets its own page and the caption shows its position, such as (1/2). Panel labels continue across pages and start again at (a) for each new call. Figures are captured when you call add_plot.
TikZ / PGFPlots graphs
add_tikz_plot accepts one PyLaTeX Plot or an iterable of plots and draws them on a single axis. It uses the existing PyLaTeX dependency and requires the tikz and pgfplots packages in your TeX installation.
The graph type is selected with standard PGFPlots options:
| Graph | Plot(options=...) |
axis_options / data |
|---|---|---|
| Lines / smooth curves | mark=none / smooth,mark=none |
Ordered (x, y) pairs, or a func expression |
| Scatter | only marks |
(x, y) pairs |
| Vertical / horizontal bars | Optional colors | ybar / xbar; horizontal bars use (value, position) |
| Grouped bars | One plot per series | ybar or xbar, shared category positions |
| Stacked bars | One plot per series | ybar stacked or xbar stacked |
| Steps | const plot,mark=none |
Sort by x; each value extends to the next x |
| Stems | ycomb or xcomb |
Numeric pairs |
| Symmetric error bars | error bars/.cd,y dir=both,y explicit |
error_bar=[(x_error, y_error), ...], one pair per point |
| Logarithmic axes | Any compatible plot style | xmode=log and/or ymode=log; positive values on each log axis |
| Histogram | ybar interval,fill=blue!30 |
Compute counts in Python; pairs of left bin edge and count, followed by (last_edge, 0) |
Coordinates must be numeric. Represent categories with positions such as 1, 2, 3 and set xtick / xticklabels (or their y equivalents). This helper covers 2D plots; it has no dedicated API for 3D, heatmaps, pie charts, or box plots. See the PGFPlots plot types and error bars documentation for option details.
DataFrame table, model curve, and scatter
This example uses illustrative load-test data from the same DataFrame for a table and a graph, alongside a simple latency model:
import pandas as pd
from pylatex import Plot
from pylatex_report import LatexReport
measurements = pd.DataFrame(
{
"Concurrent users": [10, 25, 50, 75, 100],
"Latency (ms)": [31.0, 39.5, 53.0, 67.5, 86.0],
"Stddev (ms)": [1.5, 2.0, 3.2, 4.1, 5.0],
}
)
report = LatexReport(
"load_test",
"API latency",
"Engineering team",
table_of_contents=False,
separate_cover=False,
)
report.add_section("Load test")
report.add_text("Illustrative load-test measurements.")
report.add_table(measurements, "Latency by concurrent user count", precision=1)
report.add_tikz_plot(
[
Plot(name="Model", func="25 + 0.5*x"),
Plot(
name="Observations",
coordinates=measurements[["Concurrent users", "Latency (ms)"]].itertuples(
index=False, name=None
),
options="only marks",
),
],
"Observed latency and model",
axis_options=(
r"width=0.85\linewidth,height=5.5cm,grid=major,"
"xlabel={Concurrent users},ylabel={Latency (ms)},"
"domain=0:100,legend pos=north west"
),
)
print(report.generate_report("reports"))
Polars table and grouped or stacked bars
The following snippets reuse report and Plot above. Insert them before generate_report to include them in the same PDF. Here, each row describes a processing stage; both series use the same numeric positions.
import polars as pl
jobs = pl.DataFrame(
{
"Position": [1, 2, 3],
"Stage": ["Validate", "Predict", "Export"],
"First attempt": [940, 910, 970],
"Retried": [60, 90, 30],
}
)
report.add_table(jobs.drop("Position"), "Completed jobs by stage", precision=0)
report.add_tikz_plot(
[
Plot(name=column, coordinates=jobs.select("Position", column).iter_rows())
for column in ("First attempt", "Retried")
],
"Completed jobs: first attempt and retries",
axis_options=(
r"width=0.85\linewidth,height=5cm,ybar,ymin=0,"
"bar width=12pt,enlarge x limits=0.25,"
"xtick={1,2,3},xticklabels={Validate,Predict,Export},"
"ylabel={Jobs},legend style={at={(0.5,1.05)},anchor=south,legend columns=2}"
),
)
Replace ybar with ybar stacked to show each stage's total of 1,000 completed jobs, split by first attempt and retry.
Mean latency with error bars
Reuse the load-test DataFrame to draw the mean latency with its sample standard deviation. The first error coordinate is zero because the user count has no uncertainty here.
report.add_tikz_plot(
Plot(
name="Mean latency",
coordinates=measurements[["Concurrent users", "Latency (ms)"]].itertuples(
index=False, name=None
),
error_bar=((0, std) for std in measurements["Stddev (ms)"]),
options="mark=*,error bars/.cd,y dir=both,y explicit",
),
"Mean latency with sample standard deviation",
axis_options=(
r"width=0.85\linewidth,height=5cm,grid=major,"
"xlabel={Concurrent users},ylabel={Latency (ms)},legend pos=north west"
),
)
The ML example computes these summaries from repeated runs rather than entering them by hand. The fund example builds a Polars histogram table with numpy.histogram and an empirical cumulative distribution, then plots the counts as intervals and the probabilities as steps. Their rendered PDFs are linked in Examples.
Each plot supplies either a nonempty func expression or nonempty coordinates of finite numeric (x, y) pairs. Functions use PGFPlots syntax, such as x^2, rather than Python callables. Plot data and options are captured when add_tikz_plot is called, including coordinates supplied as an iterator.
axis_options and Plot.options preserve PGFPlots/LaTeX syntax, including commands such as \linewidth; plain text captions and legend names are escaped. Escape LaTeX special characters yourself in raw options, such as \% in tick labels. Omitting axis_options uses an axis width of 0.9\linewidth and a height of 6cm; supplying it replaces those defaults, so include the dimensions you want. This method creates one figure with one axis; use add_plot for Matplotlib mosaics.
Report style
Reuse a ReportStyle across reports to apply the same branding. Put your own logo at logo.png in your working directory, or download the example logo and save it under that name.
from pylatex_report import CoverPage, LatexReport, ReportStyle
style = ReportStyle(
logo="logo.png",
accent_color="#126D77",
header="Horizon Research",
footer="Simulated data",
cover=CoverPage(label="Research report", subtitle="Model comparison"),
)
report = LatexReport("comparison", "Model comparison", "Research team", style=style)
Logos can be PNG, JPEG or PDF. A custom cover uses the report title, author and date, with page numbering starting on the next page. Set page_numbers=False on the style to hide page numbers. The constructor options table_of_contents, separate_cover and section_page_break control pagination. For custom LaTeX, use the underlying PyLaTeX document at report.doc.
Output and diagnostics
generate_report("reports") returns the PDF path. By default, it publishes only the finished PDF and cleans up temporary compilation files on success or failure. Use keep_intermediates=True to retain a build directory with the .tex file, figures, logo and LaTeX log. To recompile an example from its retained build directory, run latexmk -pdf report.tex.
When latexmk is unavailable, pdflatex runs until the auxiliary files for references and contents stop changing, with a maximum of five passes. If they do not stabilize, generation raises an error and preserves any existing destination PDF. Use keep_intermediates=True to inspect the build files.
The API validates inputs with Pydantic. Pass columns=3 as an integer. A string such as columns="3" raises a ValidationError.
Development
Clone the repository as shown in Examples, then run these commands from its root. uv sync --locked installs the library in editable mode along with the development and example dependencies.
uv sync --locked
uv run --locked pre-commit install
uv run --locked pre-commit run --all-files
Run pre-commit install once per clone. The hooks use Ruff for linting and formatting checks and ty for static type checking. To apply formatting locally, run uv run --locked ruff format.
uv run --locked python -B -m pytest
The suite includes integration tests that compile PDFs and skips them when pdflatex is unavailable. Use -m "not integration" to run unit tests only or --keep-test-artifacts to keep generated test files for debugging.
GitHub Actions runs unit tests on Python 3.10 and 3.15 with freshly resolved dependencies. A third environment on Python 3.10 uses --resolution lowest-direct to test the minimum compatible versions of the declared direct dependencies. These jobs install only the runtime dependencies and the test dependency group; they do not use or modify uv.lock.
A single Python 3.12 job installs LaTeX and runs pre-commit, the full test suite with locked dependencies, and the installed-distribution check. The distribution check builds a wheel and a source distribution, rebuilds a second wheel from that source distribution, and installs each wheel with its runtime dependencies in a separate fresh environment. Each installation must import the public API and compile a PDF from outside the checkout, with Python's isolated mode enabled. Run the same check locally with uv and LaTeX available:
bash scripts/check_distribution.sh
Pass a new output directory to retain the tested wheel and source archive, for example bash scripts/check_distribution.sh dist. The script refuses an existing destination and exports files only after both installation checks succeed.
After updating a dependency with uv lock --upgrade-package <name>, rerun the checks.
To enforce these checks on the default branch, wait for the first successful run, then create an active branch ruleset under Settings → Rulesets. Require a pull request and require all four status checks: Quality and tests, Python 3.10 / highest, Python 3.15 / highest, and Python 3.10 / lowest-direct. GitHub ruleset documentation
Publishing a release
The publication workflow runs when a GitHub release is published. It reuses the full test workflow on the release's commit, verifies that the tag equals v followed by the version in pyproject.toml, and checks the distribution metadata and README rendering. Once every check passes, a separate job publishes the exact wheel and source archive tested by CI. Pushes and pull requests run tests only.
Trusted Publishing tells PyPI which GitHub repository, workflow, and environment may publish this package. GitHub supplies proof of that identity during the publication job, and PyPI grants temporary upload credentials. You do not need a permanent API token or a password stored in the repository.
Configure it once before the first publication:
- In the GitHub repository, open Settings → Environments → New environment. Enter
pypiand click Configure environment. This is a named publication destination in GitHub, not a local Python virtual environment. The workflow already refers to this name. Leave optional settings at their defaults for the initial setup; no environment secret is required. - Sign in to PyPI, open Your account → Publishing, and find the form for adding a new pending publisher. Select GitHub and enter these values:
| Field | Value |
|---|---|
| PyPI project name | pylatex-report |
| Repository owner | HaroldGueneau |
| Repository name | pylatex-report |
| Workflow filename | publish.yml |
| Environment name | pypi |
Use the GitHub repository owner, even if your PyPI username is different. The workflow field takes only publish.yml, without .github/workflows/. Click Add and check that the publisher appears in the pending publishers list.
The pending status is expected: the package does not exist on PyPI yet. The first successful publication creates it and activates the publisher automatically, so no manual project creation or initial upload is needed. Registering a pending publisher does not reserve the package name.
For each release, update the version in pyproject.toml and run uv lock if the version changed. Commit and push the release changes, then wait for CI to pass. Publish a GitHub release with a matching tag, such as v0.1.0 for version 0.1.0. The workflow and all release changes must be present in that tagged commit. For the first release, also remove the temporary pre-publication notice and GitHub installation fallback at the top of this README.
Follow the Publish to PyPI run in GitHub Actions. After it succeeds, verify the published version from a fresh environment outside this repository, including PDF generation with the quickstart. Later fixes need a new version and tag; published distribution files cannot be replaced.
If only the publication job fails, fix the PyPI configuration or transient issue and choose Re-run failed jobs to reuse the same tested archives, which are retained for seven days.
License
Distributed under the MIT license.
Metadata
Release files for pylatex-report 0.1.0
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | Provenance | Actions |
|---|---|---|---|---|
| pylatex_report-0.1.0.tar.gz | 43.4 kB | Without provenance | Details for pylatex_report-0.1.0.tar.gz |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| pylatex_report-0.1.0-py3-none-any.whl | Python 3 | none | any | Details for pylatex_report-0.1.0-py3-none-any.whl |
Total release size: 65.6 kB
Release files / pylatex_report-0.1.0.tar.gz
| Download URL | pylatex_report-0.1.0.tar.gz |
|---|---|
| Size | 43.4 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
7d7ed9aa56c89fdc05428813b46d6f21f0f69e3eaf10d0e1bb71cba098755224
|
|
BLAKE2b-256 checksum How to use checksums |
bb826ca349362df09dae82d5b9c39b021287c73f2f8ce952787b0f5b692704c1
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
uv/0.13.8 {"installer":{"name":"uv","version":"0.13.8","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"24.04","id":"noble","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":true}
|
Release files / pylatex_report-0.1.0-py3-none-any.whl
| Download URL | pylatex_report-0.1.0-py3-none-any.whl |
|---|---|
| Size | 22.2 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
75a5d3838ecffb49b5fed965aa8b03532fcc3a373e325dfe0c3983f5359d020e
|
|
BLAKE2b-256 checksum How to use checksums |
eb96d006dd94b693be1e9bf3986d289d006cff6f04903fb2b91c516109541ce9
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
uv/0.13.8 {"installer":{"name":"uv","version":"0.13.8","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"24.04","id":"noble","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":true}
|
Security for pylatex-report 0.1.0
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
No provenance found
None of the files in this release were uploaded with provenance metadata.
A note on package security
PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.
To learn more about protecting yourself from malicious actors, visit our package security documentation.