puppeteersharp
HTML to PDF and page screenshots in .NET with PuppeteerSharp and headless Chrome. Use when code or a review renders an invoice, a report, or another HTML page to PDF, or touches PuppeteerSharp, Puppeteer.LaunchAsync, BrowserFetcher, chrome-headless-shell, PdfDataAsync, SetContentAsync, GoToAsync, --no-sandbox, Chrome in a Docker image, or user text in rendered HTML. Not for end-to-end UI tests with Playwright (dev-stack:dotnet-testing), PDF libraries without a browser (QuestPDF, PdfPig), or Node Puppeteer.
- License 许可
- MIT
- 最近更新
- 2026-11-13
- Stars
- ★ 0
- Forks
- 0
01 前言 Front Matter
- name
- puppeteersharp
- metadata
- { "verified": "2026-10-27", "versions": "PuppeteerSharp 25.15.0 (Chrome.DefaultBuildId 155.0.8059.84), chrome-headless-shell 155, .NET 10.0.14 (SDK 10.0.403), aspnet:10.0 (Ubuntu 24.04) images" }
- description
- HTML to PDF and page screenshots in .NET with PuppeteerSharp and headless Chrome. Use when code or a review renders an invoice, a report, or another HTML page to PDF, or touches PuppeteerSharp, Puppeteer.LaunchAsync, BrowserFetcher, chrome-headless-shell, PdfDataAsync, SetContentAsync, GoToAsync, --no-sandbox, Chrome in a Docker image, or user text in rendered HTML. Not for end-to-end UI tests with Playwright (dev-stack:dotnet-testing), PDF libraries without a browser (QuestPDF, PdfPig), or Node Puppeteer.
02 资源文件 12
- 参考文档references/container.md5.3 KB
- 参考文档references/decisions.md1.5 KB
- 参考文档references/language.md4.7 KB
- 参考文档references/review-checklist.md3.7 KB
- 参考文档references/sources.md7.2 KB
- 参考文档references/stack-rules.md7.6 KB
- 参考文档references/testing.md3.4 KB
- 参考文档references/untrusted-content.md3.8 KB
- 参考文档rules.json6.7 KB
- 脚本scripts/convert.py2.9 KB
- 脚本scripts/doccheck.py28.8 KB
- 脚本scripts/stackcheck.py11.9 KB
03 SKILL.md 正文
PuppeteerSharp
HTML to PDF with PuppeteerSharp and headless Chrome: the browser lifetime, pages, concurrency, the PDF options, untrusted content, the container image, and the sandbox. The Dockerfile base rules are in the Docker skill. The secure coding rules (SSRF, output encoding) are in dev-stack:secure-coding. This skill adds what Chrome needs.
First
- Read
references/stack-rules.md. - Find the
PuppeteerSharpversion in*.csprojorDirectory.Packages.props. Each version has one Chrome build:PuppeteerSharp.BrowserData.Chrome.DefaultBuildId(155.0.8059.84 for 25.15.0, 155.0.8059.79 for 25.14.0). Upgrade the package and the Chrome build together. - Find where Chrome comes from:
ExecutablePath, the environment variablePUPPETEER_EXECUTABLE_PATH, orBrowserFetcher. Without the first two, PuppeteerSharp looks in the app folder. WithHeadlessMode.Shell, the path is<app folder>/ChromeHeadlessShell/Linux-<build>/. With the defaultHeadlessMode.True, it uses theChromefolder instead. - Find the content: own templates only, or text from users (a note, a name, an address). Text from users makes the HTML untrusted.
- Find each
PdfOptionsin the existing code that the change touches. Find the page size of the team (for example a decision such as DOC-01). Check both against rules 15 and 16.
Done when you can name the PuppeteerSharp version, the Chrome build and its source, and whether the HTML holds user text. You can also name the page size and PrintBackground of each existing PdfOptions.
Defaults for new code
Ask the human before you apply a default that has no accepted decision (stack rule 4). The full entries are in references/decisions.md.
| Area | Default | ID |
|---|---|---|
| Renderer | PuppeteerSharp for HTML to PDF. Playwright when the team already runs it for end-to-end tests. | - |
| Browser | chrome-headless-shell, HeadlessMode.Shell, installed at image build time. |
- |
| Content | HTML with user text is untrusted: encode it, inline all assets, block the network. | - |
| Sandbox | Non-root user, sandbox on. --no-sandbox only with an ADR and only for trusted templates. |
SEC-24 |
| Image | The renderer gets its own image on full aspnet:10.0, not chiseled. |
OPS-03 |
| Concurrency | 4 pages per process, from configuration. | - |
Existing code keeps its style (stack rule 3).
Rules
Browser and pages
- Keep one browser per process in a singleton. It launches on first use, launches again when
IsConnectedis false, and closes at host shutdown (IAsyncDisposable). A launch costs 1 to 2 seconds and a process tree. - Use one
IBrowserContextper job and one page per render, both withawait using. The context isolates cookies and storage, and the dispose ends the renderer process. - Limit concurrent renders with a
SemaphoreSlim(default 4) and let the rest wait. Each page is a renderer process, so unbounded renders end in an out-of-memory kill. - Set a timeout on each wait:
SetContentOptions.Timeout,PdfOptions.Timeout,WaitForSelectorOptions.Timeout. The page methods take noCancellationToken: pass the token to the semaphore wait. - Return
PdfDataAsyncorPdfStreamAsync. Do not write a temp file withPdfAsync(path).
public sealed class InvoiceRenderer(IOptions<InvoiceOptions> options) : IAsyncDisposable
{
private readonly SemaphoreSlim _launch = new(1, 1);
private readonly SemaphoreSlim _pages = new(options.Value.MaxConcurrentPages);
private IBrowser? _browser;
public async Task<byte[]> RenderAsync(string html, CancellationToken ct)
{
await _pages.WaitAsync(ct);
try
{
var browser = await GetBrowserAsync(ct);
await using var context = await browser.CreateBrowserContextAsync();
await using var page = await context.NewPageAsync();
await page.SetJavaScriptEnabledAsync(false);
await page.SetContentAsync(html, new SetContentOptions { Timeout = 15_000 });
return await page.PdfDataAsync(new PdfOptions { Format = PaperFormat.A4, PrintBackground = true, Timeout = 30_000 });
}
finally
{
_pages.Release();
}
}
private async Task<IBrowser> GetBrowserAsync(CancellationToken ct)
{
if (_browser is { IsConnected: true })
{
return _browser;
}
await _launch.WaitAsync(ct);
try
{
if (_browser is not { IsConnected: true })
{
if (_browser is not null)
{
await _browser.DisposeAsync();
}
_browser = await Puppeteer.LaunchAsync(new LaunchOptions
{
HeadlessMode = HeadlessMode.Shell,
ExecutablePath = options.Value.ChromePath, // null: PUPPETEER_EXECUTABLE_PATH
Allowlist = ["data:*", "about:blank"], // rule 7: no network
Timeout = 30_000,
});
}
return _browser;
}
finally
{
_launch.Release();
}
}
public async ValueTask DisposeAsync()
{
if (_browser is not null)
{
await _browser.DisposeAsync();
}
_launch.Dispose();
_pages.Dispose();
}
}
Register it with AddSingleton<InvoiceRenderer>(). The host disposes it at shutdown.
Untrusted content
- Encode each user value with the template engine:
HtmlEncoder.Default.Encode(note), or a Razor component throughHtmlRenderer. Concatenated user text is markup: it changes the layout and can load resources. - Block the network of the page when the HTML holds user text. Use
LaunchOptions.Allowlist = ["data:*", "about:blank"](Chrome 149 and later). Or use request interception that aborts each URL that is notdata:orabout:blank. Inline the CSS, fonts, and images (the logo too) as data URIs or embedded resources. Without the block, an<img>,<link>,<script>,<iframe>, or<object>makes the server request internal URLs (SSRF). - Turn JavaScript off (
SetJavaScriptEnabledAsync(false)) when the document does not need it, and add a Content Security Policy<meta>tag (default-src 'none'; img-src data:; style-src 'unsafe-inline'). - Do not pass a URL from a request to
GoToAsync. Render your own template. When a page must come from a URL, allow only a fixed list ofhttpshosts. Never allowfile:,chrome:, or an internal address.
Detail, the interception code, and the logo: references/untrusted-content.md.
Container and sandbox
- Run Chrome as a non-root user (
USER $APP_UID) with the sandbox on (SEC-24). As root, Chrome refuses to start ("Running as root without --no-sandbox is not supported"). That is why generated code adds--no-sandbox. Without the sandbox, a renderer exploit runs code in your container. - Docker's default seccomp profile blocks the sandbox of a non-root Chrome ("No usable sandbox!"). Run the container with a seccomp profile that also allows
clone,clone3, andunshare. Do not use--no-sandbox,SYS_ADMIN, orseccomp=unconfinedinstead. - Install
chrome-headless-shellat image build time, pinned toChrome.DefaultBuildId, and setPUPPETEER_EXECUTABLE_PATH. Do not callBrowserFetcher.DownloadAsync()at startup: each container then downloads Chrome over the network. - Build the renderer on full
aspnet:10.0(OPS-03): a chiseled image has no package manager for the Chrome libraries. Install fonts (fonts-liberation,fonts-noto-core), setLANG, and start with an init process (tini), so that Chrome child processes are reaped. - Keep
HeadlessMode.Shell(orTrue) outside a developer machine. NoHeadless = false, noDevtools = true.
The Dockerfile, the seccomp profile, and Kubernetes settings: references/container.md.
PDF options
These defaults give a wrong PDF with no error. Existing code often has them.
- Set
Format(orWidthandHeight) in eachPdfOptions. Without it, PuppeteerSharp prints Letter (612 x 792 points), not A4. A CSS@page { size: A4 }counts only withPreferCSSPageSize = true. - Set
PrintBackground = truewhen the template has a background color or image. The default isfalse: header bars and row colors disappear, and white text on a dark bar becomes invisible. - Name each
PdfOptionsdefect of existing code in the report (stack rule 3). Put a fixed defect under "Changes" and a defect that stays under "Open points".
The checked facts: references/sources.md.
Never write
| Wrong | Correct |
|---|---|
Args = ["--no-sandbox", "--disable-setuid-sandbox"] "for Docker" |
USER $APP_UID and a seccomp profile that allows clone, clone3, unshare |
ENV PUPPETEER_DANGEROUS_NO_SANDBOX=true |
The same: non-root user, sandbox on |
await new BrowserFetcher().DownloadAsync(BrowserFetcher.DefaultChromiumRevision); |
Build-time install and PUPPETEER_EXECUTABLE_PATH (the symbol does not exist: CS0117) |
await using var browser = await Puppeteer.LaunchAsync(...) in each request |
A singleton browser, a context per job |
await page.WaitForTimeoutAsync(500); |
A real wait condition (the method does not exist: CS1061) |
page.WaitForXPathAsync("//h1") |
page.WaitForSelectorAsync("xpath///h1") (CS0618) |
SetContentAsync(html, new NavigationOptions { WaitUntil = [Networkidle0] }) |
SetContentAsync(html, new SetContentOptions { Timeout = 15_000 }) (CS0618) |
await page.PdfAsync("invoice.pdf"); then read the file |
await page.PdfDataAsync(options) |
await page.PdfDataAsync(); or new PdfOptions { Timeout = 30_000 } |
new PdfOptions { Format = PaperFormat.A4, PrintBackground = true, Timeout = 30_000 } |
$"<p>{order.CustomerNote}</p>" |
$"<p>{HtmlEncoder.Default.Encode(note)}</p>" and a blocked network |
<img src="https://cdn.example.com/logo.png"> with a blocked network |
The logo as a data URI or an embedded resource |
await page.GoToAsync(request.Url); |
Your own template, or an allow list of https hosts |
FROM mcr.microsoft.com/dotnet/aspnet:10.0-noble-chiseled for the renderer |
FROM mcr.microsoft.com/dotnet/aspnet:10.0 plus libraries, fonts, tini |
Node syntax: headless: 'new', page.pdf({ path }) |
HeadlessMode = HeadlessMode.Shell, PdfDataAsync |
Check
-
Build with the warnings as errors (CS0618 marks the obsolete APIs):
dotnet build -warnaserrorPass:
Build succeededwith 0 warnings. -
Run the integration tests with
PUPPETEER_EXECUTABLE_PATHset to the pinnedchrome-headless-shell:dotnet test. Pass: the PDF starts with%PDF-, and its/MediaBoxis A4 (about 596 x 842 points, not 612 x 792). A local HTTP listener gets no request from a note with<img src="http://127.0.0.1:<port>/x">. Content that never ends fails within the timeout. Test setup:references/testing.md. -
Lint the Dockerfile:
hadolint Dockerfile. Pass: no DL3002 (the last user is not root). -
Smoke-test the image: run it with the production seccomp profile and render one page with the sandbox on. Pass: a PDF, and no "No usable sandbox" in the log.
-
Run the rules of this skill:
python3 <skill folder>/scripts/stackcheck.py --root <repo>Pass: 0 errors. For each warning, fix it or add
// stackcheck: ignore <RULE-ID> <reason>.
Review checklist
The full list is in references/review-checklist.md.
- No
--no-sandbox,--disable-setuid-sandbox, orPUPPETEER_DANGEROUS_NO_SANDBOXwithout an ADR (SEC-24). tool (PPTR-NO-SANDBOX) - The image runs as a non-root user. tool (hadolint DL3002), judge
- No
BrowserFetcherdownload at runtime. Chrome is installed at build time and pinned. tool (PPTR-RUNTIME-DOWNLOAD), judge - One browser per process, a context and a page per render, disposed. tool (PPTR-BROWSER-PER-CALL), judge
- Concurrent renders are limited. judge
- User values are HTML-encoded. judge
- The network of the page is blocked when the HTML holds user text. Assets are inlined. judge
- No request URL reaches
GoToAsyncwithout a host allow list. judge - JavaScript is off when the document does not need it. judge
- Timeouts on
SetContentAsync, waits, andPdfDataAsync. tool (CS0618 for the old options), judge PdfDataAsyncorPdfStreamAsync, no temp file. tool (PPTR-PDF-FILE)- Headless in all non-local settings. tool (PPTR-HEADFUL)
- The image has fonts,
LANG, and an init process, on fullaspnet:10.0. judge - An integration test proves the PDF, the blocked network, and the timeout. judge
- Each
PdfOptionssets the page size andPrintBackground, also in existing code that the change touches. tool (PPTR-PDF-FORMAT, PPTR-PDF-BACKGROUND), judge
Report
End with the report of stack rule 8 (references/stack-rules.md): the same headings in the same order on each run.
References
references/decisions.md: read before new code needs the SEC-24 decision. It has the question, the options, and the recommendation.references/untrusted-content.md: read when the HTML holds user text, when the page loads a remote asset, or when code callsGoToAsync.references/container.md: read before you write or review a Dockerfile, a compose file, or a Kubernetes manifest for the renderer.references/testing.md: read before you write a test that renders a PDF, or set up CI for it.references/review-checklist.md: read for a full review.references/sources.md: the primary sources and the credits.references/stack-rules.mdandreferences/language.md: the common rules and the output language. Output followsreferences/language.md.scripts/stackcheck.py: the rule check of this skill.
04 同仓库更多 Skills
web-accessibility
Web accessibility to WCAG 2.2 AA - a checklist for the design, the tool checks (axe-core, the Tab walk, reduced motion), and the manual checks that no tool does (screen reader, zoom, status messages) - with the EAA and EN 301 549 status. Use when a design, mockup, or built feature must be checked for accessibility, when a review must cover keyboard and screen reader use, when the user asks about focus, a focus trap, contrast, or a screen reader on a page, or when the user asks which accessibility rules apply.
ux-states
State inventory for each screen - default, empty, loading, partial, error, success, disabled, overflow, offline, and the business states (no permission, stale data, locked by another user, waiting on an external system, bulk result with failures, read only) - with what the user sees, can do, and how the user recovers. Use when a screen or flow needs its states designed or checked, or when a design shows only the happy path.
ux-setup
Set up a project for UX work - finds the design tools, the design-system source, the brand files, the languages, and the run command, asks the human one round of questions, and writes the "## Design" section of .claude/rules/delivery.md that the ux-design commands and the ux-designer agent read. Moves an older "## Design" section out of CLAUDE.md. Use when /setup, /ux-design, or /ux-review needs the design facts, when the ux-designer agent returns NEEDS_HUMAN because the "## Design" section is missing, or when the user wants to set up or change the design tools of a project.
ux-review
UX review of a built feature against its approved design - Playwright walks each flow and state at 390, 820, and 1440 px, axe-core and the tell checks run on each state, and each heuristic gets a verdict - with findings by owner, severity, and origin, and a verdict in ux-review.md in the work folder of the item. Use when a built feature or screen must be checked against its design, mockups, or prototype, in each state or at each screen size, when built screens need findings by severity, when the build of an item with a UX design is done, or when existing screens need a UX audit.
ux-prototype
Clickable prototype of a designed story in the proto-shell standard, with variants for an A/B test, all states in scope, three sizes, and a test plan with tasks. Use when a design or mockups exist and the team must test the flow or compare variants with users before the build.
ux-practice
The method of the ux-designer agent for the UX design of a story, a feature, or a screen - Double Diamond phases, a design spec with a source for each decision, the UX decision log, evidence tags, severity, and the modes light, full, and new-direction. Preloaded by the ux-designer agent. Use when the ux-designer agent or another UX skill names this method. For the design of an item, a person starts ux-design:ux-design.