Switch PDF generation from Typst to WeasyPrint to match typst-templates layout.

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
2026-07-18 14:48:29 +03:30
parent 6159e46da8
commit e3980c5777
10 changed files with 725 additions and 58 deletions

1
.gitignore vendored
View File

@@ -6,5 +6,6 @@ _output/
*.typ *.typ
!templates/**/*.typ !templates/**/*.typ
/.quarto/ /.quarto/
.venv-pdf/
**/*.quarto_ipynb **/*.quarto_ipynb

View File

@@ -4,13 +4,21 @@ Quarto templates for Kimia Razi Persian (RTL) business reports.
One `.qmd` source renders to: One `.qmd` source renders to:
- **HTML** — simple RTL reading layout (no PDF chrome) - **HTML** — simple RTL reading layout (no print chrome on screen)
- **PDF** — via Typst (`format: typst`), with print-oriented layout - **PDF** — via WeasyPrint from the HTML, matching `typst-templates` page chrome (sidebar, header, title block, tables)
## Requirements ## Requirements
- [Quarto](https://quarto.org/) 1.9+ (bundles Typst) - [Quarto](https://quarto.org/) 1.7+
- Fonts in `assets/fonts/` (`IRNazanin`, `IRZar`, `IRLotus`) - [WeasyPrint](https://weasyprint.org/) (for PDF)
- Fonts in `assets/fonts/` (`IRNazanin`, `IRZar`, …)
Install WeasyPrint once in this repo:
```bash
uv venv .venv-pdf
uv pip install --python .venv-pdf/bin/python weasyprint
```
## Quick start ## Quick start
@@ -19,7 +27,7 @@ quarto render examples/travel-report.qmd
quarto render examples/product-test.qmd quarto render examples/product-test.qmd
``` ```
Outputs land in `_output/` (HTML + PDF). Outputs land in `_output/` (HTML + PDF). PDF is produced by `scripts/html-to-pdf.py` in `project.post-render`.
## Report types ## Report types
@@ -32,9 +40,11 @@ Outputs land in `_output/` (HTML + PDF).
``` ```
_quarto.yml _quarto.yml
styles/report.css # HTML RTL theme styles/report.css # HTML screen theme
templates/typst/ # Typst PDF partials styles/print.css # PDF / print (typst-templates match)
assets/fonts/ # Persian fonts filters/print-chrome.lua # title block + sidebar injection
scripts/html-to-pdf.py # WeasyPrint post-render
assets/fonts/
assets/logo.png assets/logo.png
examples/travel-report.qmd examples/travel-report.qmd
examples/product-test.qmd examples/product-test.qmd
@@ -42,6 +52,6 @@ examples/product-test.qmd
## Notes ## Notes
- HTML does **not** visually match the PDF (no sidebar/header parity; tables may differ). - PDF layout targets `typst-templates` (`product_test_template.typ` / `travel-report-template.typ`): A4, RTL, rotated left sidebar with page `n / N`, running header on page 2+, content-sized tables with grey header row.
- This repo rewrites `typst-templates` (pure Typst PDF library) for Quarto HTML + Typst PDF. - HTML on screen stays a simple reading view; print chrome is `display: none` until print/PDF.
- Typst helpers such as `general_info_table` / `pigment_result_block` become ordinary Markdown tables in `.qmd` sources. - Typst is not used for PDF generation.

View File

@@ -1,35 +1,20 @@
project: project:
type: default type: default
output-dir: _output output-dir: _output
post-render:
- scripts/html-to-pdf.py
format: format:
html: html:
lang: fa lang: fa
dir: rtl dir: rtl
theme: none theme: none
css: styles/report.css css:
- styles/report.css
- styles/print.css
embed-resources: true embed-resources: true
toc: false toc: false
filters: filters:
# print-chrome must run before html-no-extra-meta (needs author names)
- filters/print-chrome.lua
- filters/html-no-extra-meta.lua - filters/html-no-extra-meta.lua
typst:
lang: fa
mainfont: IRNazanin
fontsize: 13pt
papersize: a4
margin:
left: 2cm
right: 2cm
top: 2.5cm
bottom: 2.5cm
page-numbering: "۱"
font-paths:
- assets/fonts
template-partials:
- templates/typst/typst-template.typ
- templates/typst/typst-show.typ
- templates/typst/page.typ
filters:
- filters/ltr-spans.lua
- filters/typst-linebreaks.lua
- filters/summary-box.lua

View File

@@ -22,7 +22,6 @@ format:
<dt>تیم اعزامی</dt><dd>دیاکو سلطانپور</dd> <dt>تیم اعزامی</dt><dd>دیاکو سلطانپور</dd>
<dt>تاریخ</dt><dd>شروع: ۰۵/۰۲/۲۷ — پایان: ۰۵/۰۲/۲۸</dd> <dt>تاریخ</dt><dd>شروع: ۰۵/۰۲/۲۷ — پایان: ۰۵/۰۲/۲۸</dd>
</dl> </dl>
typst: default
--- ---
# گزارش مأموریت # گزارش مأموریت

View File

@@ -1,5 +1,6 @@
-- Keep YAML author for Typst/PDF (sidebar + document metadata), -- Keep YAML author/title for print-chrome.lua injection,
-- but strip it from HTML so the page does not show more than the PDF body. -- but strip Quarto's visible title block (we render our own for PDF;
-- screen readers still get the document <title>).
function Meta(meta) function Meta(meta)
if quarto.doc.is_format("html") then if quarto.doc.is_format("html") then
meta.author = nil meta.author = nil
@@ -7,3 +8,25 @@ function Meta(meta)
end end
return meta return meta
end end
function Pandoc(doc)
if not quarto.doc.is_format("html") then
return doc
end
-- Drop Pandoc title-block header nodes if present in blocks
local out = {}
for _, block in ipairs(doc.blocks) do
local skip = false
if block.t == "Header" and block.level == 1 and doc.meta.title ~= nil then
local title = pandoc.utils.stringify(doc.meta.title)
if pandoc.utils.stringify(block.content) == title then
skip = true
end
end
if not skip then
table.insert(out, block)
end
end
doc.blocks = out
return doc
end

209
filters/print-chrome.lua Normal file
View File

@@ -0,0 +1,209 @@
-- Inject typst-templates-style title block + sidebar into HTML for WeasyPrint PDF.
-- Screen CSS hides .print-only; print.css shows them.
local function stringify(v)
if v == nil then
return ""
end
if type(v) == "string" then
return v
end
return pandoc.utils.stringify(v)
end
local function escape_html(s)
s = stringify(s)
s = s:gsub("&", "&amp;")
s = s:gsub("<", "&lt;")
s = s:gsub(">", "&gt;")
s = s:gsub('"', "&quot;")
return s
end
local function meta_list_join(meta_val, sep)
if meta_val == nil then
return ""
end
if pandoc.utils.type(meta_val) == "List" then
local parts = {}
for _, item in ipairs(meta_val) do
local t = stringify(item)
if t ~= "" then
table.insert(parts, t)
end
end
return table.concat(parts, sep or " - ")
end
return stringify(meta_val)
end
local function author_names(meta)
if meta.author == nil then
return ""
end
local authors = meta.author
if pandoc.utils.type(authors) ~= "List" then
authors = { authors }
end
local names = {}
for _, a in ipairs(authors) do
if type(a) == "table" and a.name ~= nil then
table.insert(names, stringify(a.name))
else
local n = stringify(a)
if n ~= "" then
table.insert(names, n)
end
end
end
return table.concat(names, " - ")
end
local function path_exists(path)
if path == nil or path == "" then
return false
end
local f = io.open(path, "rb")
if f then
f:close()
return true
end
return false
end
local function resolve_logo_path(logo)
if logo == nil or logo == "" then
return nil
end
if path_exists(logo) then
return logo
end
local candidates = {}
if quarto.project ~= nil and quarto.project.directory ~= nil then
table.insert(candidates, pandoc.path.join({ quarto.project.directory, logo }))
end
if quarto.doc ~= nil and quarto.doc.input_file ~= nil then
local input_dir = pandoc.path.directory(quarto.doc.input_file)
table.insert(candidates, pandoc.path.join({ input_dir, logo }))
end
local cwd = pandoc.system.get_working_directory()
if cwd ~= nil then
table.insert(candidates, pandoc.path.join({ cwd, logo }))
end
for _, candidate in ipairs(candidates) do
if path_exists(candidate) then
return candidate
end
end
return logo
end
local function file_to_data_uri(path)
if path == nil or path == "" then
return nil
end
local f = io.open(path, "rb")
if not f then
return nil
end
local data = f:read("*a")
f:close()
if data == nil or data == "" then
return nil
end
local ok, encoded = pcall(pandoc.pipe, "base64", { "-w0" }, data)
if not ok or encoded == nil or encoded == "" then
ok, encoded = pcall(pandoc.pipe, "base64", {}, data)
if ok and encoded then
encoded = encoded:gsub("%s+", "")
end
end
if not ok or encoded == nil or encoded == "" then
return nil
end
local mime = "image/png"
if path:match("%.jpe?g$") then
mime = "image/jpeg"
elseif path:match("%.svg$") then
mime = "image/svg+xml"
end
return "data:" .. mime .. ";base64," .. encoded
end
function Meta(meta)
if not quarto.doc.is_format("html") then
return meta
end
local company = escape_html(meta.company or "کیمیا رازی")
local title = escape_html(meta.title or "")
local subtitle = escape_html(meta.subtitle or "")
local logo_path = resolve_logo_path(stringify(meta.logofile or "assets/logo.png"))
local logo_uri = file_to_data_uri(logo_path)
local destinations = escape_html(meta_list_join(meta.destinations, " - "))
local purpose = stringify(meta.purpose)
local report_date = escape_html(meta["report-date"] or meta.date or "")
local authors = escape_html(author_names(meta))
local subtitle_html = ""
if subtitle ~= "" then
subtitle_html = ' <span class="subtitle">| ' .. subtitle .. "</span>"
end
local logo_html = ""
local running_logo = ""
if logo_uri ~= nil then
logo_html = '<img class="logo" src="' .. logo_uri .. '" alt="" />'
running_logo = '<img src="' .. logo_uri .. '" alt="" />'
elseif logo_path ~= nil and logo_path ~= "" then
local src = escape_html(logo_path)
logo_html = '<img class="logo" src="' .. src .. '" alt="" />'
running_logo = '<img src="' .. src .. '" alt="" />'
end
-- Logo first (left), title text second (right) — matches product_test_template.typ
local title_block = string.format([[
<div class="print-title-block print-only">
%s
<div class="title-text">
<p class="company-line">%s%s</p>
<p class="report-title">%s</p>
</div>
</div>
]], logo_html, company, subtitle_html, title)
-- Rotated sidebar labels; page chip comes from print.css @page @bottom-left.
local sidebar = string.format([[
<div class="print-sidebar print-only" aria-hidden="true">
<div class="seg">%s</div>
<div class="seg">%s</div>
</div>
]], destinations, title)
local running = string.format([[
<div class="print-running-header print-only" aria-hidden="true">
%s
<span>%s</span>
<span class="pipe">|</span>
<span>%s</span>
</div>
]], running_logo, company, subtitle)
local travel = ""
if purpose ~= nil and purpose ~= "" then
travel = string.format([[
<div class="print-travel-meta print-only">
<hr class="rule" />
<h2>اطلاعات کلی</h2>
<div class="meta-row"><div class="meta-label">مقصد:</div><div class="meta-value">%s</div></div>
<div class="meta-row"><div class="meta-label">هدف مأموریت:</div><div class="meta-value">%s</div></div>
<div class="meta-row"><div class="meta-label">تیم اعزامی:</div><div class="meta-value">%s</div></div>
<div class="meta-row"><div class="meta-label">تاریخ:</div><div class="meta-value">%s</div></div>
<hr class="rule" />
</div>
]], destinations, escape_html(purpose), authors, report_date)
end
quarto.doc.include_text("before-body", running .. sidebar .. title_block .. travel)
return meta
end

View File

@@ -1,24 +1,5 @@
-- Render ::: {.summary-box} as a Typst block matching HTML table chrome. -- ::: {.summary-box} is styled by CSS for HTML/PDF (WeasyPrint).
-- No AST rewrite needed.
function Div(el) function Div(el)
if not el.classes:includes("summary-box") then return nil
return nil
end
if not quarto.doc.is_format("typst") then
return nil
end
local inner = pandoc.write(pandoc.Pandoc(el.content), "typst")
inner = inner:gsub("^%s+", ""):gsub("%s+$", "")
local typst = string.format([[
#block(
width: 100%%,
inset: 12pt,
radius: 8pt,
stroke: 0.5pt + rgb("#d0d7de"),
fill: rgb("#f6f8fa"),
)[
%s
]
]], inner)
return pandoc.RawBlock("typst", typst)
end end

74
scripts/html-to-pdf.py Executable file
View File

@@ -0,0 +1,74 @@
#!/usr/bin/env python3
"""Convert Quarto HTML outputs to PDF with WeasyPrint (typst-templates layout)."""
from __future__ import annotations
import os
import sys
from pathlib import Path
def venv_python() -> Path | None:
here = Path(__file__).resolve()
for root in (here.parents[1], here.parents[2]):
py = root / ".venv-pdf" / "bin" / "python"
if py.is_file() and os.access(py, os.X_OK):
return py
return None
def ensure_weasyprint():
try:
import weasyprint # noqa: F401
return
except ImportError:
pass
py = venv_python()
if py is None:
print(
"html-to-pdf: WeasyPrint not found. Install with:\n"
" uv venv .venv-pdf && uv pip install --python .venv-pdf/bin/python weasyprint",
file=sys.stderr,
)
raise SystemExit(1)
os.execv(str(py), [str(py), str(Path(__file__).resolve()), *sys.argv[1:]])
def collect_html_files(project_dir: Path, output_dir: Path) -> list[Path]:
# Quarto passes rendered output paths as argv after the script name.
from_args = []
for arg in sys.argv[1:]:
p = Path(arg)
if not p.is_absolute():
p = (project_dir / p).resolve()
if p.suffix.lower() == ".html" and p.is_file() and "files" not in p.parts:
from_args.append(p)
if from_args:
return sorted(set(from_args))
html_files = sorted(output_dir.rglob("*.html"))
return [p for p in html_files if "files" not in p.parts]
def main() -> int:
ensure_weasyprint()
from weasyprint import HTML
project_dir = Path(os.environ.get("QUARTO_PROJECT_DIR", Path.cwd()))
output_dir = Path(os.environ.get("QUARTO_PROJECT_OUTPUT_DIR", project_dir / "_output"))
html_files = collect_html_files(project_dir, output_dir)
if not html_files:
print("html-to-pdf: no HTML files found to convert", file=sys.stderr)
return 0
for html_path in html_files:
pdf_path = html_path.with_suffix(".pdf")
print(f"html-to-pdf: {html_path} -> {pdf_path}")
HTML(filename=str(html_path), base_url=str(html_path.parent)).write_pdf(str(pdf_path))
return 0
if __name__ == "__main__":
raise SystemExit(main())

378
styles/print.css Normal file
View File

@@ -0,0 +1,378 @@
/* Print / PDF styles matching typst-templates product_test_template.typ */
@font-face {
font-family: "IRNazanin";
src: url("../assets/fonts/IRNazanin.ttf") format("truetype");
font-weight: normal;
font-style: normal;
}
@font-face {
font-family: "IRNazanin";
src: url("../assets/fonts/IRNazanin-Bold.ttf") format("truetype");
font-weight: bold;
font-style: normal;
}
@font-face {
font-family: "IRZar";
src: url("../assets/fonts/IRZar.ttf") format("truetype");
font-weight: normal;
font-style: normal;
}
@font-face {
font-family: "IRZar";
src: url("../assets/fonts/IRZar-Bold.ttf") format("truetype");
font-weight: bold;
font-style: normal;
}
:root {
--text: #000000;
--header-fill: #ebebeb; /* ~luma(235) */
--stroke: #000000;
}
@page {
size: A4;
/* Extra left margin for rotated sidebar; bottom-left box = typst page chip */
margin: 2.5cm 2cm 2.5cm 2.8cm;
@bottom-center {
content: counter(page);
font-family: "IRNazanin", sans-serif;
font-size: 11pt;
}
@top-center {
content: element(report-header);
width: 100%;
}
/* WeasyPrint only updates counter(page) reliably in @page margin boxes
(not inside position:fixed). Place the black n/N chip at bottom-left. */
@bottom-left {
content: counter(page) " / " counter(pages);
font-family: "IRZar", "IRNazanin", sans-serif;
font-size: 11pt;
color: #fff;
background: #000;
border: 1pt solid #000;
width: 28pt;
height: 20pt;
text-align: center;
vertical-align: middle;
margin-left: -1.6cm;
direction: ltr;
}
}
@page :first {
@top-center {
content: none;
}
}
@media print {
html {
direction: rtl;
}
body {
font-family: "IRNazanin", sans-serif;
font-size: 13pt;
line-height: 1.2;
color: var(--text);
background: #ffffff;
margin: 0;
padding: 0;
text-align: justify;
hyphens: auto;
max-width: none;
}
/* Hide Quarto / screen chrome in PDF */
#title-block-header,
header#title-block-header,
.quarto-title-block,
.quarto-title,
.quarto-title-meta,
.quarto-title-meta-contents,
header.quarto-title-block,
h1.title,
p.subtitle,
nav.toc-active,
#TOC,
.sidebar.sidebar-navigation,
#quarto-sidebar,
#quarto-margin-sidebar,
#quarto-back-to-top,
.report-meta,
.screen-only {
display: none !important;
}
/* ===== Running header (page > 1) ===== */
/* RTL flex: first child (logo) packs to the right — matches typst header grid */
.print-running-header {
position: running(report-header);
display: flex;
flex-direction: row;
align-items: center;
justify-content: flex-start;
gap: 5pt;
width: 100%;
font-family: "IRNazanin", sans-serif;
font-size: 11pt;
padding-bottom: 4pt;
border-bottom: 0.5pt solid black;
direction: rtl;
}
.print-running-header img {
height: 19pt;
width: auto;
border: 1pt solid black;
}
.print-running-header .pipe {
margin: 0 2pt;
}
/* ===== Left rotated sidebar (every page) ===== */
.print-sidebar {
position: fixed;
left: 0.25cm;
/* Leave room at the bottom for the @page bottom-left page chip */
bottom: 3.4cm;
width: 16.5cm;
height: 20pt;
transform-origin: left bottom;
transform: rotate(-90deg);
display: flex;
flex-direction: row;
align-items: stretch;
font-family: "IRZar", "IRNazanin", sans-serif;
font-size: 13pt;
border-bottom: 1pt solid black;
direction: ltr;
z-index: 1000;
}
.print-sidebar .seg {
flex: 1 1 0;
display: flex;
align-items: center;
justify-content: center;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
padding: 0 6pt;
direction: rtl;
}
/* Page chip is drawn via @page @bottom-left (counters don't update in fixed) */
.print-sidebar .pagebox {
display: none;
}
/* ===== Title block (first page) ===== */
/* LTR flex: logo (first) on left, title text (second) on right — typst grid */
.print-title-block {
display: flex;
flex-direction: row;
justify-content: space-between;
align-items: flex-start;
width: 100%;
margin: 0 0 16pt 0;
direction: ltr;
}
.print-title-block .title-text {
direction: rtl;
text-align: right;
line-height: 0.95;
flex: 1 1 auto;
}
.print-title-block .company-line {
font-size: 21pt;
font-weight: bold;
margin: 0;
}
.print-title-block .company-line .subtitle {
font-size: 14pt;
font-weight: normal;
}
.print-title-block .report-title {
font-size: 14pt;
font-weight: bold;
margin: 2pt 0 0 0;
}
.print-title-block .logo {
height: 1.8cm;
width: auto;
}
/* Travel-report meta block (only when purpose is set) */
.print-travel-meta {
margin: 12pt 0 24pt 0;
}
.print-travel-meta .rule {
border: none;
border-top: 1pt solid black;
margin: 10pt 0;
}
.print-travel-meta h2 {
font-size: 1.4em;
text-align: center;
margin: 8pt 0;
border: none;
padding: 0;
}
.print-travel-meta .meta-row {
display: flex;
gap: 2em;
margin: 10pt 0;
justify-content: flex-start;
direction: rtl;
}
.print-travel-meta .meta-label {
flex: 0 0 8em;
text-align: right;
}
.print-travel-meta .meta-value {
flex: 1;
font-weight: bold;
text-align: right;
}
/* ===== Headings ===== */
h1, h2, h3, h4 {
font-family: "IRNazanin", sans-serif;
font-weight: bold;
text-align: right;
line-height: 1.35;
page-break-after: avoid;
}
/* Level-1/2 headings get a full-width rule above (typst show heading) */
h1, h2 {
font-size: 14pt;
margin: 16pt 0 10pt 0;
padding-top: 8pt;
border-top: 1pt solid black;
}
/* First body heading after Quarto title header: no rule (typst skips at top) */
#title-block-header + h1,
.print-title-block + h1,
.print-travel-meta + h1 {
border-top: none !important;
padding-top: 0 !important;
margin-top: 8pt;
}
h3 {
font-size: 13pt;
margin: 12pt 0 8pt 0;
border: none;
}
p {
margin: 0.4em 0 0.7em 0;
text-align: justify;
}
ul, ol {
margin: 0.4em 0 0.8em 0;
padding-right: 1.4em;
padding-left: 0;
}
li {
margin: 0.2em 0;
text-align: justify;
}
/* ===== Tables (typst: 0.5pt stroke, header luma fill, content-sized) ===== */
table {
border-collapse: collapse;
width: auto;
max-width: 100%;
margin: 10pt auto;
border: 0.5pt solid var(--stroke);
font-size: 12.5pt;
page-break-inside: avoid;
}
th, td {
border: 0.5pt solid var(--stroke);
padding: 7pt 8pt;
text-align: center;
vertical-align: middle;
}
thead th,
tr:first-child th {
background: var(--header-fill);
font-weight: bold;
color: var(--text);
}
table [dir="ltr"],
table .ltr {
direction: ltr;
unicode-bidi: isolate;
display: inline-block;
}
/* Summary box */
.summary-box {
border: 0.5pt solid #d0d7de;
border-radius: 8pt;
background: #f6f8fa;
padding: 10pt 12pt;
margin: 10pt 0;
page-break-inside: avoid;
}
.summary-box > :first-child {
margin-top: 0;
}
.summary-box > :last-child {
margin-bottom: 0;
}
.summary-box [dir="ltr"],
.summary-box .ltr {
direction: ltr;
unicode-bidi: isolate;
display: inline-block;
}
code {
direction: ltr;
unicode-bidi: embed;
font-size: 0.95em;
}
a {
color: inherit;
text-decoration: none;
}
main, .content, #quarto-content, .page-columns, .page-body {
margin: 0 !important;
padding: 0 !important;
max-width: none !important;
}
} /* @media print */

View File

@@ -143,3 +143,10 @@ code {
direction: ltr; direction: ltr;
unicode-bidi: embed; unicode-bidi: embed;
} }
/* Print chrome is injected for WeasyPrint PDF; hide on screen */
@media screen {
.print-only {
display: none !important;
}
}