diff --git a/CLAUDE.md b/CLAUDE.md
index f26d60e..69b6885 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -44,6 +44,15 @@ npm run test:watch # vitest
- `POST /convert/markdown-to-pdf` — render Markdown to PDF; returns `application/pdf` bytes,
or `{ pdfBase64, bytes }` with `Accept: application/json` / `?format=base64` (for embedding
in a GraphQL response — the shape `hadron-server`'s `nodeExport` PDF path consumes).
+- `POST /convert/html-to-pdf` — render HTML to PDF; same response shapes,
+ auth and page geometry as `markdown-to-pdf`. JSON `{ html, options? }`, or a raw `text/html` body
+ when no options are needed. The HTML is rendered **verbatim** — no wrapper, no default
+ stylesheet — whether it is a complete document or a bare fragment Chromium completes. This
+ direction exists for output that is a *layout* rather than prose
+ (certificate, invoice, report cover), where the Markdown path's wrapper fights the caller's own
+ positioning. `options.css` is appended after the document's own styles; `options.title` sets the
+ download filename only, since the document already carries a `
`. Wraps the same
+ `htmlToPdf()` the Markdown path calls as its second stage, so it adds no rendering capability.
- `POST /convert/markdown-to-html` — render Markdown to a complete, self-contained HTML document
(inline print CSS, no external fetches); returns `text/html` bytes, or `{ html, bytes }` with
`Accept: application/json` / `?format=json`. Consumer: `hadron-server`'s `nodeExport` HTML phase
diff --git a/README.md b/README.md
index fc3b0f0..56999fa 100644
--- a/README.md
+++ b/README.md
@@ -13,7 +13,10 @@ platform and why the boundary is drawn here.
| Method | Path | Purpose |
|---|---|---|
| `POST` | `/convert/markdown-to-pdf` | Render Markdown to a PDF |
+| `POST` | `/convert/html-to-pdf` | Render an HTML document to a PDF |
+| `POST` | `/convert/markdown-to-html` | Render Markdown to a self-contained HTML document |
| `POST` | `/convert/pdf-to-markdown` | Extract Markdown text from a PDF |
+| `POST` | `/convert/html-to-markdown` | Convert content HTML to Markdown |
| `GET` | `/convert/info` | Service capabilities (no secrets) |
| `GET` | `/healthz` | Liveness |
| `GET` | `/readyz` | Readiness (+ whether Chromium is warm) |
@@ -51,6 +54,53 @@ curl -sS -X POST http://localhost:8080/convert/markdown-to-pdf \
-o out.pdf
```
+### `POST /convert/html-to-pdf`
+
+For documents that are a **layout** rather than prose — a certificate, an
+invoice, a report cover, a badge. Routing those through Markdown means embedding
+raw HTML in Markdown and fighting the converter over what it escapes, wraps or
+reflows; here your HTML is rendered **verbatim**, with no wrapper and no default
+stylesheet. Usually that is a complete document — a bare fragment works too,
+since Chromium supplies the missing structure.
+
+Request (JSON), or a raw `text/html` body when you don't need options:
+
+```jsonc
+{
+ "html": "…",
+ "options": {
+ "title": "Certificate", // filename only — the document has its own
+ "format": "A4", // A4 | A3 | A5 | Letter | Legal | Tabloid
+ "landscape": true,
+ "printBackground": true,
+ "margin": { "top": "0mm", "right": "0mm", "bottom": "0mm", "left": "0mm" },
+ "css": "@page { size: A4 landscape }" // optional, appended AFTER your styles
+ }
+}
+```
+
+Response: identical to `markdown-to-pdf` — `application/pdf` bytes by default,
+or `{ "pdfBase64": "...", "bytes": 12345 }` with `Accept: application/json` or
+`?format=base64`.
+
+```bash
+curl -sS -X POST http://localhost:8080/convert/html-to-pdf \
+ -H 'content-type: application/json' \
+ -H "authorization: Bearer $PDF_SERVICE_TOKEN" \
+ -d '{"html":"Hello
","options":{"landscape":true}}' \
+ -o out.pdf
+```
+
+**Inline your assets as `data:` URIs.** Rendering runs with JavaScript disabled
+and, unless `PDF_ALLOW_REMOTE=true`, every non-`data:` request is aborted — so a
+background image or signature referenced by URL renders as nothing and still
+returns `200`. Inlining also makes the render deterministic and offline, which
+matters for a document people keep.
+
+**Fonts are the image's, not yours.** A document naming a typeface the container
+does not have falls back silently. Embed the face as a `data:` URI `@font-face`
+if exact typography matters.
+
### `POST /convert/pdf-to-markdown`
Send the PDF either as a raw `application/pdf` body or as JSON
diff --git a/src/lib/htmlToPdf.ts b/src/lib/htmlToPdf.ts
index b0adb8b..6ef7848 100644
--- a/src/lib/htmlToPdf.ts
+++ b/src/lib/htmlToPdf.ts
@@ -4,15 +4,41 @@ import { config } from '../config.js';
import type { PdfOptions } from '../types.js';
/**
- * Render a complete HTML document to PDF bytes using the shared headless
- * browser. Each call gets its own page, which is always closed.
+ * Render an HTML document to PDF bytes using the shared headless browser. Each
+ * call gets its own page, which is always closed.
*
* Security hardening: JavaScript is disabled (the document is static print
* content), and unless PDF_ALLOW_REMOTE is set, every non-inline request is
* aborted — only `data:` and the initial `about:blank`/document load proceed.
* That blocks `file://` reads and remote (SSRF) fetches via crafted Markdown.
+ *
+ * `extraCss` is applied to the PARSED DOCUMENT, after `setContent`, never by
+ * concatenating it to the source string. The Markdown path does not use it —
+ * `markdownToHtml` bakes `options.css` into the document it builds — so it is
+ * only the HTML path, where the source is the caller's and cannot be edited
+ * safely, that passes it.
+ *
+ * Why it has to be the DOM. Deciding where a `` neutralization that the string form needed:
+ * DOM text content cannot close an element, so caller CSS containing ``
+ * is now just CSS.
*/
-export async function htmlToPdf(html: string, options: PdfOptions): Promise {
+export async function htmlToPdf(
+ html: string,
+ options: PdfOptions,
+ extraCss?: string,
+): Promise {
const browser = await getBrowser();
const page = await browser.newPage();
try {
@@ -34,7 +60,37 @@ export async function htmlToPdf(html: string, options: PdfOptions): Promise: a caller may carry
+ // a MARKER
'],
+ // Would block an injected inline style, silently, without a CSP bypass.
+ [
+ 'a restrictive Content-Security-Policy',
+ '
' +
+ '
',
+ ],
+ ];
+
+ for (const [label, html] of cases) {
+ const res = await request(app)
+ .post('/convert/html-to-pdf?format=base64')
+ .send({ html, options: { css: 'p{display:none}' } });
+ expect(res.status, label).toBe(200);
+
+ const md = await request(app)
+ .post('/convert/pdf-to-markdown')
+ .set('content-type', 'application/pdf')
+ .send(Buffer.from(res.body.pdfBase64, 'base64'));
+ expect(md.status, label).toBe(200);
+ expect(md.body.markdown, `${label}: the stylesheet reached the document`).not.toContain(
+ 'MARKER',
+ );
+ }
+ });
});
diff --git a/src/routes/convert.ts b/src/routes/convert.ts
index e3f932c..fbe144d 100644
--- a/src/routes/convert.ts
+++ b/src/routes/convert.ts
@@ -7,6 +7,7 @@ import {
PdfToMarkdownSchema,
PdfOptionsSchema,
HtmlToMarkdownSchema,
+ HtmlToPdfSchema,
MarkdownToHtmlSchema,
MAX_HTML_CHARS,
} from '../types.js';
@@ -58,6 +59,71 @@ convertRouter.post(
},
);
+/**
+ * POST /convert/html-to-pdf
+ * Body: JSON { html: string, options?: PdfOptions }, OR a raw text/html payload
+ * (which takes the default options, since there is nowhere to carry them).
+ * Returns: application/pdf bytes by default, or { pdfBase64, bytes } when the
+ * client sends `Accept: application/json` or `?format=base64`.
+ *
+ * The caller's HTML is rendered VERBATIM — nothing is wrapped, nothing is
+ * restyled. Typically that is a complete document; a bare fragment also works,
+ * since Chromium supplies the missing structure. That is the point of this
+ * direction: it is for output that is a layout rather than prose, where the
+ * Markdown path's wrapper and default stylesheet would fight the caller's own
+ * positioning. Everything else matches markdown-to-pdf: same auth, same page
+ * geometry, same JavaScript-disabled and remote-blocked rendering.
+ */
+convertRouter.post(
+ '/html-to-pdf',
+ async (req: Request, res: Response, next: NextFunction) => {
+ try {
+ let html: string;
+ // Explicitly undefined: the raw text/html mode carries no options, and
+ // `?? {}` below turns that into the documented defaults.
+ let options: unknown = undefined;
+ const contentType = req.get('content-type') ?? '';
+
+ if (contentType.includes('text/html')) {
+ if (typeof req.body !== 'string' || req.body.length === 0) {
+ throw new HttpError(400, 'empty text/html body');
+ }
+ // Enforce the same cap the JSON schema applies, so both modes match.
+ if (req.body.length > MAX_HTML_CHARS) {
+ throw new HttpError(413, `html body exceeds ${MAX_HTML_CHARS} characters`);
+ }
+ html = req.body;
+ } else {
+ const parsed = HtmlToPdfSchema.parse(req.body);
+ html = parsed.html;
+ options = parsed.options;
+ }
+
+ const opts = PdfOptionsSchema.parse(options ?? {});
+ const pdf = await htmlToPdf(html, opts, opts.css);
+
+ const wantsJson =
+ req.query.format === 'base64' || req.accepts(['application/pdf', 'application/json']) === 'application/json';
+
+ logger.info('html-to-pdf', { bytes: pdf.length, format: opts.format, json: wantsJson });
+
+ if (wantsJson) {
+ res.json({ pdfBase64: pdf.toString('base64'), bytes: pdf.length });
+ return;
+ }
+
+ res
+ .status(200)
+ .setHeader('Content-Type', 'application/pdf')
+ .setHeader('Content-Length', pdf.length)
+ .setHeader('Content-Disposition', `inline; filename="${(opts.title || 'document').replace(/[^\w.-]/g, '_')}.pdf"`)
+ .send(pdf);
+ } catch (err) {
+ next(err);
+ }
+ },
+);
+
/**
* POST /convert/markdown-to-html
* Body: { markdown: string, options?: { title, css } }
@@ -171,7 +237,7 @@ convertRouter.post(
convertRouter.get('/info', (_req, res) => {
res.json({
service: 'hadrontool-pdf',
- directions: ['markdown-to-pdf', 'markdown-to-html', 'pdf-to-markdown', 'html-to-markdown'],
+ directions: ['markdown-to-pdf', 'html-to-pdf', 'markdown-to-html', 'pdf-to-markdown', 'html-to-markdown'],
allowRemote: config.allowRemote,
authRequired: Boolean(config.serviceToken),
});
diff --git a/src/types.ts b/src/types.ts
index aa85260..e3e8283 100644
--- a/src/types.ts
+++ b/src/types.ts
@@ -38,6 +38,28 @@ export const MarkdownToPdfSchema = z.object({
export type MarkdownToPdfRequest = z.infer;
+/**
+ * JSON body shape for html->pdf (alternative to a raw text/html body).
+ *
+ * The caller's HTML is rendered verbatim — usually a complete document, though
+ * a bare fragment works too, since Chromium supplies the missing structure.
+ * Nothing is wrapped and nothing is restyled. This is the direction to use when
+ * the output is a *layout* rather than prose (a certificate, an invoice, a
+ * report cover), where routing through Markdown would mean fighting the
+ * converter over what it escapes, wraps or reflows.
+ *
+ * Shares `PdfOptionsSchema` with markdown-to-pdf so page geometry behaves
+ * identically. `css` is appended to the caller's own styles rather than
+ * replacing them; `title` sets the download filename only, since the document
+ * already carries its own ``.
+ */
+export const HtmlToPdfSchema = z.object({
+ html: z.string().min(1, 'html must not be empty').max(MAX_HTML_CHARS),
+ options: PdfOptionsSchema.optional(),
+});
+
+export type HtmlToPdfRequest = z.infer;
+
/**
* Options for markdown->HTML. A subset of PdfOptions — only the two fields that
* affect the HTML document itself apply; page geometry (format/margin/...) is