Node.js

npm 包 weblitzpdf 就是面向 Node.js 的 Weblitz:把 HTML、文件或网址转为 PDF、Excel、Word 或 PowerPoint 文件或图片,像 Chrome 一样打印,无需安装、启动或驱动浏览器。同一个包还能渲染 RDLC 和 RDL 报表以及 Markdown。它的选项就是 Puppeteer 的 page.pdf() 选项,名称相同。

安装

npm install weblitzpdf

版本 2.0.0-rc.2,2.0 的预发布版。需要 Node.js 22 或更高版本,支持 Linux(glibc,x64、Arm64)、macOS(Arm64、x64)和 Windows(x64、Arm64)。npm 只会以可选依赖的形式安装适合你平台的引擎(@weblitzpdf/linux-x64, @weblitzpdf/linux-arm64, @weblitzpdf/darwin-arm64, @weblitzpdf/darwin-x64, @weblitzpdf/win32-x64, @weblitzpdf/win32-arm64 之一):它包含引擎及其运行所需的 .NET 运行时,因此无需再安装其他东西,机器上也不需要 .NET。

  • 使用 --omit=optional 安装会漏掉引擎,从其他平台复制过来的 node_modules(例如把 Mac 上的复制到 Linux 容器中)也一样:请在镜像中运行 npm ci。否则调用会以代码 workerMissing 失败,并指出缺少的包。
  • Alpine 和其他基于 musl 的系统暂不支持:请使用 glibc 镜像,例如 node:22-bookworm-slim。
  • 在 Linux 上,引擎需要 fontconfig 和 ICU,而精简镜像中没有它们:apt-get install -y --no-install-recommends libfontconfig1 libicu72(ICU 包的编号随系统版本而定)。

你的第一批 PDF

import { readFile, writeFile } from 'node:fs/promises';
import { pathToFileURL } from 'node:url';
import { renderHtml, renderUrl } from 'weblitzpdf';   // or: const { renderHtml, renderUrl } = require('weblitzpdf');

// HTML text
const invoice = await renderHtml('<h1>Invoice 42</h1><p>...</p>', { format: 'A4', printBackground: true });
await writeFile('invoice.pdf', invoice.file);

// A web page, after its scripts ran; path writes the file too, as Puppeteer's
await renderUrl('https://example.com/report', {
  path: 'report.pdf',
  margin: { top: '18mm', right: '18mm', bottom: '20mm', left: '20mm' },
});

// A file on disk: its CSS, pictures, fonts and scripts are read from its folder
const letters = await renderHtml(await readFile('templates/letters.html', 'utf8'), {
  baseUrl: pathToFileURL('templates/').href,
});

// What could not be drawn or loaded is said, never thrown
for (const note of invoice.notes) console.log(`${note.severity} ${note.code}: ${note.message}`);

一次渲染返回 { file, contentType, extension, pages, notes, elapsedMs, trial },其中 file 是 Buffer。除了 Puppeteer 的选项(format、width、height、landscape、margin、preferCSSPageSize、printBackground、scale、pageRanges、displayHeaderFooter、headerTemplate、footerTemplate、path),引擎还有自己的选项:baseUrl、output、scripts、network、title、author、pdfA、compression、locale、timeZone、now、useInstalledFonts、styles、hide、consent: 'hide' 和 ads: 'block'。它们就是 .NET 的选项,采用 JavaScript 的命名。

Excel、Word、PowerPoint 和图片

const workbook = await renderUrl('https://example.com/prices', { output: 'xlsx' });   // or 'docx', 'pptx'
const shot = await renderUrl('https://example.com', { output: 'png', viewport: { width: 1280, height: 720, deviceScaleFactor: 2 } });
const pages = await renderHtml(html, { output: 'png', capture: 'pages', format: 'A4' });   // pages.file is a ZIP

output: 'png'(或 'jpeg'、'webp'、'tiff')绘制页面而不是打印它:页面图片。Office 文件的说明见 Excel、Word 和 PowerPoint。

页面会加载什么

默认情况下,页面不会从网络加载任何内容,但对于 renderUrl,允许其自身的主机。network 可开放更多,并为需要登录的页面提供请求头、Cookie 和凭据;每一项只发送到它指定的主机(allowedHosts: ['*'] 允许任意主机):

await renderUrl('https://app.example.com/reports/42', {
  network: {
    allowedHosts: ['app.example.com', 'cdn.example.com'],
    headers: [{ name: 'Authorization', value: `Bearer ${token}`, hosts: ['app.example.com'] }],
    cookies: [{ name: 'session', value: sessionId, domain: 'app.example.com', secure: true, httpOnly: true }],
  },
});

报表和 Markdown

同一个包也能渲染 SSRS2 的报表:renderReport、checkReport、markdownTo 和 importReport。@ssrs2/ssrs2(npm install @ssrs2/ssrs2)为只渲染报表的项目提供相同的函数;它在同一版本的 weblitzpdf 上运行。

import { renderReport, checkReport } from 'weblitzpdf';

const pdf = await renderReport({ path: 'Reports/Invoice.rdlc' }, {
  format: 'PDF',   // or WORDOPENXML, EXCELOPENXML, PPTX, IMAGE, PNG, HTML5, CSV, XML (docx, xlsx...)
  datasets: { Items: [{ Description: 'Widget', Price: 104.99, Qty: 1 }] },
  parameters: { InvoiceNumber: '42' },
});

const check = await checkReport({ path: 'Reports/Invoice.rdlc' });   // its problems, without rendering it
if (!check.ok) console.log(check.notes);

工作进程、超时和错误

引擎在工作进程中运行,这些进程在第一次调用时启动并保持预热;空闲的工作进程不会让 Node.js 一直运行。在此之前可用 configure() 设置共享池的选项,new Engine(options) 则创建另一个池,方法相同,另有 close()。

import { configure, Engine } from 'weblitzpdf';

configure({ workers: 2, timeout: 30_000 });   // milliseconds

const engine = new Engine({ workers: 4, concurrency: 2, maxQueue: 100 });
const result = await engine.renderHtml(html, { timeout: 5_000, signal: AbortSignal.timeout(10_000) });
await engine.close();

调用失败时会抛出 WeblitzError,其 code 说明原因:badRequest、tooLarge、timeout、refused、invalidReport、renderFailed、busy、cancelled、workerCrashed、workerMissing、startFailed、protocolMismatch。崩溃的工作进程只会让它正在运行的调用失败;下一次调用会启动新的进程。

在服务器上

默认情况下,工作进程使用的是你自己机器上 .NET 库的设置:页面可以打开任意主机、通过 file: 基础 URL 读取本地文件,且没有时间限制。打印他人发送的页面的服务器,应使用 SSRS2 的服务器设置启动其工作进程:这样页面只会加载其 URL 自身的主机,私有地址和 file: 会被拒绝,报表代码始终受限,渲染到 2,000 页或 120 秒时停止。

configure({ env: { SSRS2_WORKER_POLICY: 'service' } });

// changed as JSON over those settings: 500 pages at most, and pages may open cdn.example.com
configure({
  env: {
    SSRS2_WORKER_POLICY: 'service',
    SSRS2_WORKER_SETTINGS: JSON.stringify({ maxPages: 500, network: { allowedHosts: ['cdn.example.com'] } }),
  },
});

字体

引擎自带为 Arial、Helvetica、Times New Roman、Courier New、Calibri、Cambria 和 Segoe UI 绘制的字体(拉丁文、希腊文、西里尔文和希伯来文)。阿拉伯文、中文、日文、韩文、泰文、印度系文字和表情符号使用机器自己的字体绘制:macOS 和 Windows 都有这些字体,Linux 容器通常没有(apt-get install -y fonts-noto-core fonts-noto-cjk fonts-noto-color-emoji)。字体指南

许可证

SSRS2 许可证涵盖 Weblitz 和 SSRS2 的报表。通过环境变量 SSRS2_LICENSE 或 configure({ license: 'SSRS2-...' }) 提供密钥。没有密钥时,PDF 和图片的页面带有试用水印,结果的 trial 为 true。购买许可证