boxpdf-html

io.github.earonesty由 GitHub 账号 earonesty 发布v1.7.0更新于 Oct 24, 2026

Render HTML to PDF (html_to_pdf) plus boxpdf library docs and templates, for AI agents.

发布方自己的服务:captcha.cc Human Verification

已验证STDIO仅桌面文件与存储开发者工具

概览

AI 生成的概览

一个本地 stdio MCP 服务器,把编写的 HTML 渲染为静态 PDF,并向助手提供 boxpdf 库文档和模板。

可以做什么
将 HTML 字符串(可选附带 CSS)渲染为 PDF,写入指定文件路径或以 base64 资源内联返回,并始终返回警告和不支持的 CSS 诊断。按主题查询 boxpdf 使用指南,例如快速入门、字体、主题、表格、分页、流式处理、HTML API 和 Cloudflare。读取内置资源:一份指南、若干说明文档,以及五个文档模板(收据、登机牌、简历、订单确认、证书)。
适用场景
当助手需要在不使用浏览器的情况下,把发票、收据、报告、邮件等编写的文档 HTML 转成静态 PDF,并希望在同一服务器中获得库使用指南和起步模板时使用。
运行要求
以 stdio 本地进程运行,例如通过 npx 启动,需要 Node.js 和该 npm 包。未声明账号、API 密钥或环境变量。除非启用 allowRemote 选项,否则远程 http(s) 图片会被阻止。
安装前请注意
html_to_pdf 工具会以代理的文件系统权限写入 outputPath,应只指向预期位置。启用 allowRemote 后服务器会抓取远程图片。PDF 密码加密通过环境变量名配置,而非命令行参数值。渲染并非浏览器:不执行 JavaScript,部分 CSS 不受支持。

安装

在 SourceWeft 中

  1. 打开 控制台中的 boxpdf-html,将其添加到工作区。
  2. 为需要使用其工具的对话启用该服务。

Desktop only,通过 STDIO。 STDIO 服务会启动本地进程,因此需要 SourceWeft 桌面宿主。

其他 MCP 客户端

参照 仓库 中的启动说明。

README

@boxpdf/html-reader

Readable HTML-to-PDF rendering built on @boxpdf/writer. It is for invoices, receipts, reports, emails, and other authored document HTML where a useful static PDF matters more than browser pixel emulation.

sh
npm install @boxpdf/html-reader @boxpdf/writer pdf-lib

The original boxpdf-html package and boxpdf-html command remain supported. They are published from the same build and at the same version as @boxpdf/html-reader. New projects should use the scoped package; existing projects do not need to change.

CLI

Render an HTML file directly:

sh
npx @boxpdf/html-reader invoice.html invoice.pdf

The scoped package also provides html-reader as a shorter command name.

With generated Tailwind CSS:

sh
npx tailwindcss -i ./tailwind.css -o ./dist/tailwind.css --minifynpx @boxpdf/html-reader invoice.html invoice.pdf --css ./dist/tailwind.css

For very large inputs, add --stream:

sh
npx @boxpdf/html-reader archive.html archive.pdf --streamtype archive.html | npx @boxpdf/html-reader - archive.pdf --stream

Streaming makes two bounded passes over the HTML: one for CSS, fonts, and images, then one for incremental layout and PDF output. Stdin is spooled to a temporary file so it can be reopened. The output replaces its destination only after a successful conversion. This path requires boxpdf 1.12.0 or newer.

With PDF 2.0 AES-256 password encryption:

sh
BOXPDF_PASSWORD='open me' \  npx @boxpdf/html-reader invoice.html invoice.pdf --password-env BOXPDF_PASSWORD

--password-env accepts an environment-variable name. The variable must be set to a non-empty password. The password value is never accepted as a command argument, which keeps it out of the command line and process listing.

With custom fonts and local images:

sh
npx @boxpdf/html-reader invoice.html invoice.pdf \  --font ./Inter-Regular.ttf \  --bold-font ./Inter-Bold.ttf \  --font-family 'Inter=normal:Inter-Regular.ttf,bold:Inter-Bold.ttf'

Useful flags:

sh
html-reader <input.html> <output.pdf>html-reader - <output.pdf>                  # read HTML from stdinhtml-reader input.html output.pdf --css app.csshtml-reader input.html output.pdf --base-url ./publichtml-reader input.html output.pdf --password-env BOXPDF_PASSWORDhtml-reader input.html output.pdf --debughtml-reader input.html output.pdf --unsupported-csshtml-reader input.html output.pdf --profilehtml-reader input.html output.pdf --stream

The CLI defaults to pdf-lib's built-in Helvetica family. Use real embedded fonts for production output when brand matching, unicode coverage, or exact metrics matter.

MCP server

boxpdf-html mcp is a stdio MCP server for AI agents. It's batteries-included: an html_to_pdf tool plus the full boxpdf library docs, so an agent never has to add a second server.

sh
claude mcp add boxpdf-html -- npx -y @boxpdf/html-reader mcp

Tools

  • html_to_pdf — render an HTML string (and optional css) to a PDF. Writes to outputPath, or returns the PDF inline as a base64 resource. Always returns warnings and unsupportedCss diagnostics so the agent can fix its input.
    • Args: html (required), css, outputPath, size (Letter/A4/Legal/Tabloid, default Letter), margin (default 40), baseUrl, fonts: { regular, bold, italic, boldItalic } (TTF/OTF paths), allowRemote (default false — http(s) image fetches are blocked unless enabled), debug.
  • boxpdf_docs — focused guidance for building PDFs with the libraries directly. topic: quickstart (default), fonts, themes, tables, pagination, streaming, html-api, cloudflare.

Resources: boxpdf-html://guide, boxpdf-html://readme, boxpdf://readme, and the five boxpdf://templates/<name> sources (receipt, boarding-pass, resume, order-confirmation, certificate).

The server runs no JavaScript and (by default) makes no network requests. outputPath writes with the agent's filesystem permissions; without it, PDFs over 1 MB are summarized rather than inlined.

API

htmlToPdf — one call to bytes

htmlToPdf(html, options?) is the simplest path: it creates the document, embeds fonts, renders, and returns the PDF bytes. Fonts default to the built-in Helvetica family, so the minimal call needs no setup.

ts
import { htmlToPdf } from "@boxpdf/html-reader";
const bytes = await htmlToPdf("<h1>Invoice</h1><p>Thanks for your order.</p>");

Pass embedded fonts (via loadFont) and a resolveImage callback for production output:

ts
import { readFile } from "node:fs/promises";import { PDFDocument } from "pdf-lib";import { loadFont, loadImage } from "@boxpdf/writer";import { htmlToPdf } from "@boxpdf/html-reader";
const pdf = await PDFDocument.create();const inter = await loadFont(pdf, await readFile("Inter-Regular.ttf"));const interBold = await loadFont(pdf, await readFile("Inter-Bold.ttf"));const logo = await loadImage(pdf, await readFile("logo.png"));
const bytes = await htmlToPdf(await readFile("invoice.html", "utf8"), {  pdf,                       // reuse the document you embedded into  font: inter,  boldFont: interBold,  resolveImage: ({ url }) => (url === "logo.png" ? logo : undefined),  margin: 40});

Options: font / boldFont / italicFont / boldItalicFont (default to Helvetica), pdf (render into an existing document), margin (default 40), size (default US Letter), width (CSS containing-block width; defaults to the page's content width), debug, plus everything htmlToBoxpdf accepts (resolveFont, resolveImage, baseUrl, defaultFontSize, defaultColor, diagnostics, profile).

htmlToBoxpdf — the nodes, for full control

htmlToBoxpdf turns HTML into normal boxpdf nodes without rendering. Reach for it when you need the nodes themselves, the warnings/diagnostics, multiple render passes, or renderFlow headers/footers.

ts
import { readFile } from "node:fs/promises";import { PDFDocument } from "pdf-lib";import { loadFont, loadImage, renderFlow } from "@boxpdf/writer";import { fontFamily, htmlToBoxpdf } from "@boxpdf/html-reader";
const html = await readFile("invoice.html", "utf8");const pdf = await PDFDocument.create();
const inter = await loadFont(pdf, await readFile("Inter-Regular.ttf"));const interBold = await loadFont(pdf, await readFile("Inter-Bold.ttf"));const logo = await loadImage(pdf, await readFile("logo.png"));
const result = htmlToBoxpdf(html, {  font: inter,  boldFont: interBold,  resolveFont: fontFamily({    Inter: { normal: inter, bold: interBold },    "sans-serif": { normal: inter, bold: interBold }  }),  resolveImage: ({ url }) => (url === "logo.png" ? logo : undefined),  baseUrl: process.cwd(),  width: 532});
console.log(result.warnings);await renderFlow(pdf, result.nodes, { margin: 40 });const bytes = await pdf.save();

width is the CSS containing block width in PDF points. A US Letter page with 40pt margins has a 532pt content width, so width: 532 is a good default.

streamHtmlToPdf — bounded large-document conversion

streamHtmlToPdf accepts a function that reopens the HTML for each of its two passes and writes PDF bytes incrementally. Embed fonts before calling it; use prepare to embed images found by the resource preflight before output begins.

ts
import { createReadStream, createWriteStream } from "node:fs";import { PDFDocument, StandardFonts } from "pdf-lib";import { nodeAdapter } from "@boxpdf/writer";import { streamHtmlToPdf } from "@boxpdf/html-reader";
const pdf = await PDFDocument.create();const font = await pdf.embedFont(StandardFonts.Helvetica);
const result = await streamHtmlToPdf(  () => createReadStream("archive.html"),  nodeAdapter(createWriteStream("archive.pdf")),  { pdf, font, width: 532, margin: 40 });
console.log(result.pageCount, result.dom.maxBufferedNodes);

Ordinary block wrappers and tables are released in bounded continuation fragments. Atomic layouts such as flex/grid, positioned or transformed containers, and single uninterrupted text nodes have explicit safety caps and fail with a useful error when they cannot be streamed safely. Selectors whose meaning depends on sibling position conservatively disable wrapper fragmentation.

Fonts

Fonts are explicit. boxpdf-html does not discover system fonts and does not ship a browser font stack. This keeps rendering deterministic and works in serverless runtimes.

At minimum, pass font. Pass boldFont and italicFont if your HTML uses bold or italic text:

ts
const result = htmlToBoxpdf(html, {  font,  boldFont,  italicFont,  width: 532});

For CSS font-family, use fontFamily():

ts
const resolveFont = fontFamily({  Inter: {    normal: interRegular,    bold: interBold,    italic: interItalic,    boldItalic: interBoldItalic  },  Helvetica: {    normal: fallback,    bold: fallbackBold  },  "sans-serif": {    normal: fallback,    bold: fallbackBold  }});

The resolver receives { families, weight, style } and returns a pdf-lib PDFFont. You can provide your own resolver when you need looser mapping, font aliases, language-specific fallbacks, or weight synthesis.

Gotchas:

  • font-family: system-ui only works if your resolver maps system-ui.
  • Standard pdf-lib fonts are convenient but limited; use embedded TTF/OTF fonts for real documents.
  • Complex shaping depends on pdf-lib/fontkit behavior. Western-language invoice/report text is the target.
  • Font metrics affect layout. Use the same embedded fonts in tests and production when visual stability matters.

Tailwind CSS

Tailwind works when you render its generated CSS, not raw class names alone. The usual flow is:

  1. Write document HTML with Tailwind classes.
  2. Run Tailwind against that HTML.
  3. Inline or pass the generated CSS to boxpdf-html.
  4. Render with a containing width that matches your intended PDF content area.

Example source:

html
<div class="p-6 bg-[#f8fafc] text-gray-900">  <div class="max-w-[520px] rounded-[10px] border bg-white p-5 shadow-sm">    <div class="grid grid-cols-[1fr_2fr] gap-x-4 gap-y-3">      <div class="rounded-md border border-blue-200 bg-blue-50 p-3">        <p class="text-xs font-semibold uppercase tracking-wide text-blue-700">Status</p>        <p class="mt-1 text-sm font-bold">Paid</p>      </div>      <div class="rounded-md border border-gray-200 p-3">        <p class="text-xs font-semibold uppercase tracking-wide text-gray-600">Notes</p>        <p class="mt-1 text-sm leading-5">Two fraction column wraps later.</p>      </div>    </div>  </div></div>

Build CSS:

css
@import "tailwindcss";@source "./invoice.html";
sh
npx tailwindcss -i ./tailwind-input.css -o ./tailwind-output.css --minifynpx @boxpdf/html-reader invoice.html invoice.pdf --css ./tailwind-output.css

Supported Tailwind patterns include common spacing, color, text, border, radius, width/height, flex, grid, table, image, and arbitrary-value utilities. Unsupported utility declarations can be reported with --unsupported-css or diagnostics: { unsupportedCss: true }.

Tailwind gotchas:

  • Responsive/state variants are parsed as CSS; there is no viewport interaction. Choose a single generated CSS target for the PDF you want.
  • Two-dimensional transforms support ordered translate, scale, rotate, skew, and matrix function lists, their X/Y variants, transform-origin, and the standalone translate, rotate, and scale properties. Length/percentage translations and deg, grad, rad, and turn angles are supported. Three-dimensional transforms, shadows, filters, transitions, and browser-only effects are ignored or reported as unsupported.
  • Tailwind preflight resets are mostly harmless. Diagnostics intentionally focus on utility selectors instead of noisy base selectors.
  • If text layout matters, use the same fonts in Tailwind design review and PDF rendering.

Images

The API uses resolveImage because pdf-lib images must be embedded before rendering:

ts
const images = new Map([  ["logo.png", await loadImage(pdf, await readFile("logo.png"))]]);
htmlToBoxpdf(html, {  font,  resolveImage: ({ url }) => images.get(url),  baseUrl: process.cwd()});

The CLI preloads local, http(s), and data: image URLs referenced by <img src> and CSS url(...). Missing images preserve their layout box when width/height can be inferred.

CSS And HTML Surface

Supported:

  • HTML fragments and full documents via parse5.
  • Stylesheets and inline styles via css-tree.
  • Selectors: tag, class, id, attributes, descendants, child/sibling combinators, common structural pseudos, and escaped Tailwind selectors.
  • Cascade basics: stylesheet rules, inline style, !important, inheritance, custom properties, var(), and common calc().
  • Layout: block, inline, inline-block, inline-flex, inline-grid, flex, grid fallback, tables, floats, absolute/relative positioning, z-index, overflow hidden, and replaced images.
  • Text: rich inline runs, hard breaks, normal/no-wrap/pre-like whitespace, transforms, decoration, alignment, vertical-align, list hanging indents, and wrapping.
  • Sizing/styling: CSS px to points, pt, em/rem, vw/vh, percentages in common places, min/max widths, box-sizing, margin/padding/gap, backgrounds, background images, borders, per-side borders, border collapse, radius, object-fit.

Not a browser:

  • No JavaScript execution.
  • No interactive or dynamic layout.
  • No full browser paint model.
  • No system font discovery.
  • CSS support is intentionally expanded around static document output. Use diagnostics to find unsupported declarations in real templates.

Diagnostics

ts
const result = htmlToBoxpdf(html, {  font,  width: 532,  diagnostics: { unsupportedCss: true, sampleLimit: 3 },  profile: (event) => console.log(event.phase, event.elapsedMs)});
console.log(result.diagnostics?.unsupportedCss);

Unsupported CSS diagnostics are aggregated by property/value pair and include selector samples. Profile events cover parsing, CSS, style computation, render-tree construction, and output node counts.

Useful commands:

sh
pnpm run typecheckpnpm run testpnpm run buildpnpm run tailwind:fixturepnpm run visual:checkpnpm run pack:releaseBOXPDF_DEP_VERSION=^1.7.0 pnpm run publish:release

来源:README.md,提交 d0aa81d

工具

0
SourceWeft 尚未在沙箱中启动过该软件包,因此其工具未知。

版本历史

2
  1. v1.7.0最新Oct 9, 2026
  2. v1.6.0Sep 16, 2026

评分

已满足适用检查项的 50%

该评分衡量此收录条目的完整程度,依据注册中心条目、端点与公开来源计算得出。它不是对服务器本身的评价,也不表示服务器安全或当前可用:可连通性是带日期的检查结果,评分也不包含安装量或用户评价。

  • 近 30 天内可连通25 分

    请保持端点能够响应 MCP 握手;SourceWeft 每 30 天探测一次。

  • 已声明认证方式10 分

    请在注册中心条目中声明凭据请求头,或保持端点能够响应探测,以便判定其认证方式。

  • 已列出工具15 分

    请让服务器在无凭据时响应 tools/list,或发布可在沙箱中无凭据启动的软件包。

  • 描述必需15 分
  • 图标10 分
  • 文档15 分
  • 许可证10 分

其他 Captcha 集成