From e3980c5777a40d5bef4edfb99ce570d93d7d74de Mon Sep 17 00:00:00 2001 From: diaco Date: Sat, 18 Jul 2026 14:48:29 +0330 Subject: [PATCH] Switch PDF generation from Typst to WeasyPrint to match typst-templates layout. Co-authored-by: Cursor --- .gitignore | 1 + README.md | 32 ++- _quarto.yml | 29 +-- examples/travel-report.qmd | 1 - filters/html-no-extra-meta.lua | 27 ++- filters/print-chrome.lua | 209 ++++++++++++++++++ filters/summary-box.lua | 25 +-- scripts/html-to-pdf.py | 74 +++++++ styles/print.css | 378 +++++++++++++++++++++++++++++++++ styles/report.css | 7 + 10 files changed, 725 insertions(+), 58 deletions(-) create mode 100644 filters/print-chrome.lua create mode 100755 scripts/html-to-pdf.py create mode 100644 styles/print.css diff --git a/.gitignore b/.gitignore index 8fa8438..7103467 100644 --- a/.gitignore +++ b/.gitignore @@ -6,5 +6,6 @@ _output/ *.typ !templates/**/*.typ /.quarto/ +.venv-pdf/ **/*.quarto_ipynb diff --git a/README.md b/README.md index d0bbf28..4b28a8f 100644 --- a/README.md +++ b/README.md @@ -4,13 +4,21 @@ Quarto templates for Kimia Razi Persian (RTL) business reports. One `.qmd` source renders to: -- **HTML** — simple RTL reading layout (no PDF chrome) -- **PDF** — via Typst (`format: typst`), with print-oriented layout +- **HTML** — simple RTL reading layout (no print chrome on screen) +- **PDF** — via WeasyPrint from the HTML, matching `typst-templates` page chrome (sidebar, header, title block, tables) ## Requirements -- [Quarto](https://quarto.org/) 1.9+ (bundles Typst) -- Fonts in `assets/fonts/` (`IRNazanin`, `IRZar`, `IRLotus`) +- [Quarto](https://quarto.org/) 1.7+ +- [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 @@ -19,7 +27,7 @@ quarto render examples/travel-report.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 @@ -32,9 +40,11 @@ Outputs land in `_output/` (HTML + PDF). ``` _quarto.yml -styles/report.css # HTML RTL theme -templates/typst/ # Typst PDF partials -assets/fonts/ # Persian fonts +styles/report.css # HTML screen theme +styles/print.css # PDF / print (typst-templates match) +filters/print-chrome.lua # title block + sidebar injection +scripts/html-to-pdf.py # WeasyPrint post-render +assets/fonts/ assets/logo.png examples/travel-report.qmd examples/product-test.qmd @@ -42,6 +52,6 @@ examples/product-test.qmd ## Notes -- HTML does **not** visually match the PDF (no sidebar/header parity; tables may differ). -- This repo rewrites `typst-templates` (pure Typst PDF library) for Quarto HTML + Typst PDF. -- Typst helpers such as `general_info_table` / `pigment_result_block` become ordinary Markdown tables in `.qmd` sources. +- 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. +- HTML on screen stays a simple reading view; print chrome is `display: none` until print/PDF. +- Typst is not used for PDF generation. diff --git a/_quarto.yml b/_quarto.yml index ae0fc90..fc2d7ff 100644 --- a/_quarto.yml +++ b/_quarto.yml @@ -1,35 +1,20 @@ project: type: default output-dir: _output + post-render: + - scripts/html-to-pdf.py format: html: lang: fa dir: rtl theme: none - css: styles/report.css + css: + - styles/report.css + - styles/print.css embed-resources: true toc: false filters: + # print-chrome must run before html-no-extra-meta (needs author names) + - filters/print-chrome.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 diff --git a/examples/travel-report.qmd b/examples/travel-report.qmd index 9c218e9..4212279 100644 --- a/examples/travel-report.qmd +++ b/examples/travel-report.qmd @@ -22,7 +22,6 @@ format:
تیم اعزامی
دیاکو سلطانپور
تاریخ
شروع: ۰۵/۰۲/۲۷ — پایان: ۰۵/۰۲/۲۸
- typst: default --- # گزارش مأموریت diff --git a/filters/html-no-extra-meta.lua b/filters/html-no-extra-meta.lua index c814763..34e45c8 100644 --- a/filters/html-no-extra-meta.lua +++ b/filters/html-no-extra-meta.lua @@ -1,5 +1,6 @@ --- Keep YAML author for Typst/PDF (sidebar + document metadata), --- but strip it from HTML so the page does not show more than the PDF body. +-- Keep YAML author/title for print-chrome.lua injection, +-- but strip Quarto's visible title block (we render our own for PDF; +-- screen readers still get the document ). function Meta(meta) if quarto.doc.is_format("html") then meta.author = nil @@ -7,3 +8,25 @@ function Meta(meta) end return meta 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 diff --git a/filters/print-chrome.lua b/filters/print-chrome.lua new file mode 100644 index 0000000..be9f4b4 --- /dev/null +++ b/filters/print-chrome.lua @@ -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("&", "&") + s = s:gsub("<", "<") + s = s:gsub(">", ">") + s = s:gsub('"', """) + 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 diff --git a/filters/summary-box.lua b/filters/summary-box.lua index 8eebfda..137d2dd 100644 --- a/filters/summary-box.lua +++ b/filters/summary-box.lua @@ -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) - if not el.classes:includes("summary-box") then - 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) + return nil end diff --git a/scripts/html-to-pdf.py b/scripts/html-to-pdf.py new file mode 100755 index 0000000..0d9358d --- /dev/null +++ b/scripts/html-to-pdf.py @@ -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()) diff --git a/styles/print.css b/styles/print.css new file mode 100644 index 0000000..d1bd479 --- /dev/null +++ b/styles/print.css @@ -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 */ diff --git a/styles/report.css b/styles/report.css index 786256c..1f2d70a 100644 --- a/styles/report.css +++ b/styles/report.css @@ -143,3 +143,10 @@ code { direction: ltr; unicode-bidi: embed; } + +/* Print chrome is injected for WeasyPrint PDF; hide on screen */ +@media screen { + .print-only { + display: none !important; + } +}