October DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsClean PCRecommendedOne scan can reveal what keeps slowing WindowsLook for cleanup and repair opportunities.Run ScanOctober DealsAmazon USDeal season is back - check today's better picksAmazon US: current deals, useful picks and tech finds.See Picks×
Skip to content
.NET

How to Generate and Save Puppeteer PDFs in .NET with PuppeteerSharp

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Use PuppeteerSharp’s Page.PdfAsync(path) to generate a PDF and save it directly to a file. The basic flow is to launch Chrome in headless mode, create a page, navigate to a URL or set HTML content, and await the PDF call. PuppeteerSharp’s documentation says PDF generation is supported only in Chrome headless and uses print CSS media by default.

Generate a PDF and save it to a path

Install PuppeteerSharp in your .NET project and make sure a compatible Chrome or Chromium browser is available to launch. The API documentation does not establish one target framework for every package version, so check the package and framework requirements for the version your project uses. The example below assumes an async method in a project with PuppeteerSharp referenced:

using PuppeteerSharp;

public static async Task SavePageAsPdfAsync()
{
    using var browser = await Puppeteer.LaunchAsync(
        new LaunchOptions { Headless = true });

    using var page = await browser.NewPageAsync();
    await page.GoToAsync("https://example.com");
    await page.PdfAsync("output.pdf");
}

PdfAsync is asynchronous, so await it before the method ends or before code tries to read, move, or upload the resulting file. The overload taking a file path writes the generated PDF there; PuppeteerSharp documents that it resolves paths using GetFullPath(string). In practice, use an absolute path if you need the output location to be independent of the process’s working directory.

The browser and page are disposed when the method exits. Keeping the browser open across several captures can be useful in a larger job, but then the code that owns it must ensure each page is closed and the browser is eventually disposed, including when an operation fails.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
#1 Best Overall
Sale
Philips 24 Inch Computer Monitor FHD 100Hz VA VESA Flicker-Free, 241V8LB
  • CRISP CLARITY: This 23.8″ Philips V line monitor delivers crisp Full HD 1920x1080 visuals. Enjoy movies, shows and videos with remarkable detail
  • INCREDIBLE CONTRAST: The VA panel produces brighter whites and deeper blacks. You get true-to-life images and more gradients with 16.7 million colors
  • THE PERFECT VIEW: The 178/178 degree extra wide viewing angle prevents the shifting of colors when viewed from an offset angle, so you always get consistent colors
  • WORK SEAMLESSLY: This sleek monitor is virtually bezel-free on three sides, so the screen looks even bigger for the viewer. This minimalistic design also allows for seamless multi-monitor setups that enhance your workflow and boost productivity
  • A BETTER READING EXPERIENCE: For busy office workers, EasyRead mode provides a more paper-like experience for when viewing lengthy documents

Choose how the page is supplied

Navigate to a URL

Use GoToAsync(url) when the content is already served at a URL. The PDF is generated from the page state available after navigation completes. If the site renders content asynchronously after the initial navigation, the basic sample may capture before that content is ready; add an appropriate wait for the content your own page requires before calling PdfAsync.

Render HTML supplied by your application

For HTML you already have as a string, set it on the page rather than navigating to a remote address:

using PuppeteerSharp;

public static async Task SaveHtmlAsPdfAsync(string html)
{
    using var browser = await Puppeteer.LaunchAsync(
        new LaunchOptions { Headless = true });

    using var page = await browser.NewPageAsync();
    await page.SetContentAsync(html);
    await page.PdfAsync("output.pdf");
}

Include the styles, fonts, and other resources needed by the document in the supplied HTML or make sure the page can reach them. A PDF can only reflect the layout and assets available to the browser when it prints the page.

Understand print media before adjusting layout

PuppeteerSharp’s PDF API uses print CSS media by default. That means rules inside @media print can apply, and screen-only styling may not be used in the output. This is often desirable for documents: a site can hide navigation, change colors, or adjust spacing specifically for printing.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Rank #2
Philips 22 Inch Computer Monitor FHD 100Hz VA VESA Flicker-Free, 221V8LB
  • CRISP CLARITY: This 22 inch class (21.5″ viewable) Philips V line monitor delivers crisp Full HD 1920x1080 visuals. Enjoy movies, shows and videos with remarkable detail
  • 100HZ FAST REFRESH RATE: 100Hz brings your favorite movies and video games to life. Stream, binge, and play effortlessly
  • SMOOTH ACTION WITH ADAPTIVE-SYNC: Adaptive-Sync technology ensures fluid action sequences and rapid response time. Every frame will be rendered smoothly with crystal clarity and without stutter
  • INCREDIBLE CONTRAST: The VA panel produces brighter whites and deeper blacks. You get true-to-life images and more gradients with 16.7 million colors
  • THE PERFECT VIEW: The 178/178 degree extra wide viewing angle prevents the shifting of colors when viewed from an offset angle, so you always get consistent colors

If the PDF should use the page’s screen-media styling instead, emulate screen media before generating the PDF:

await page.EmulateMediaTypeAsync(MediaType.Screen);
await page.PdfAsync("output.pdf");

Call this after the page is created and its content is available, but before the PDF call. If the output unexpectedly differs from the browser’s normal appearance, first check the media-specific CSS and whether screen emulation is needed.

Set paper size, margins, and print options

Pass a PdfOptions object to the options overload when the default print layout is not suitable. For example:

var options = new PdfOptions
{
    Format = PaperFormat.A4,
    Landscape = false,
    PrintBackground = true,
    MarginOptions = new MarginOptions
    {
        Top = "12mm",
        Right = "12mm",
        Bottom = "16mm",
        Left = "12mm"
    }
};

await page.PdfAsync("report.pdf", options);

Use paper format for a standard sheet size, or configure paper dimensions when your document needs a custom size. Set orientation for landscape layouts. Margins reserve space around the printed page; choose values that fit your content and any header or footer.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Rank #3
Sale
Dell 24 Monitor - SE2426H - 23.8-inch FHD (1920x1080) 144Hz 1ms Display, in-Plane Switching (IPS) Technology, AMD FreeSync™, TÜV 3-Star 2X HDMI, Tilt
  • Clear visuals. Fluid motion: A 144Hz refresh rate and 1ms MPRT deliver smooth, tear‑free motion across work, gaming, and streaming for clearer, more fluid viewing.
  • Eye comfort: TÜV Rheinland 3‑star* certification reduces harmful blue light while preserving stunning color quality without compromise. *TÜV Rheinland 3-star eye comfort certification.
  • Wide viewing angle: Get consistent views across a wide 178° /178° viewing angle.
  • In-Plane Switching (IPS): See excellent color accuracy and consistency across wide viewing angles with In-plane Switching (IPS) technology.
  • Ultra-thin bezels: Maximize your viewing experience with thin bezels.
  • Backgrounds: enable background printing when the design depends on colored fills or background graphics. Without it, browser print behavior may omit those effects.
  • Page ranges: use the page-range option when you need only selected pages rather than the whole document.
  • Headers and footers: configure the header/footer templates and display option when page labels or other print furniture are required. Leave adequate margin so they do not overlap the page content.
  • Scale: adjust the scale option if content needs to fit differently, while checking that text remains readable.
  • CSS page size: the option controlling whether CSS @page size takes priority can matter when the document defines its own paper geometry.

The WaitForFonts option is documented as true by default. If you change it, consider whether the intended fonts will be ready before print layout is produced. Font availability and loading can affect line breaks and pagination.

The Tagged option requests a tagged, accessible PDF, but the PuppeteerSharp API documentation says it currently works only in old headless mode. Because that caveat can depend on the deployed Chromium and PuppeteerSharp versions, verify support in the exact environment you run rather than assuming tagged output is available in every headless configuration.

Save to a file, return bytes, or work with a stream

Choose the output method based on what the rest of your application needs. These are API alternatives; the documentation does not establish a performance advantage for one over another.

Method Use it when Result
PdfAsync(path) You want PuppeteerSharp to write a PDF file at a chosen path. A file at the resolved path.
PdfDataAsync(options) Your application needs the PDF as data, such as to upload it or return it in a response. A byte[].
PdfStreamAsync(options) The surrounding code already works with streams. A stream containing PDF output.

The data and stream methods also have overloads accepting PdfOptions. They avoid making a path the intermediate handoff when your next step consumes bytes or a stream. Choose a file path when a durable local file is the intended result; choose bytes or a stream when the application will pass the PDF directly to another component.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Rank #4
Samsung 27" Essential S3 (S36GD) Series FHD 1800R Curved Computer Monitor
  • CURVED FOR ENHANCED ENGAGEMENT: An immersive viewing experience with a curved monitor that wraps more closely around your field of vision; It creates a wider view, enhancing depth perception and minimizing peripheral distraction
  • SMOOTH PERFORMANCE FOR SEAMLESS CONTENT: Stay in the action when playing games, watching videos, or working on creative projects; The 100Hz refresh rate reduces lag and motion blur so you don't miss a thing in fast-paced moments¹
  • MORE GAMING POWER: Gain the edge with optimizable game settings; Color and image contrast can be adjusted to see scenes more vividly and spot enemies hiding in the dark; Game Mode adjusts any game to fill the screen so you can view every detail²
  • KEEP IT EASY ON THE EYES: Care for your eyes and stay comfortable, even during long sessions; Advanced eye comfort technology certified by TÜV reduces eye strain by minimizing blue light and reducing irritating screen flicker²
  • INCREASED VERSATILITY: Connect to more; Plug devices straight into your monitor for increased flexibility, making your computing environment even more convenient

Remote browser deployments

PuppeteerSharp’s examples also show connecting to a remote browser with a WebSocket endpoint and then generating a PDF. This is an architecture option when browser execution is handled elsewhere, but that example alone does not establish a particular provider, service level, or pricing model. Regardless of where Chrome runs, ensure the deployed browser supports the PDF workflow and that your application handles the returned file or data appropriately.

Troubleshoot common PDF problems

No PDF is produced or the call fails

  • Check the browser mode: PDF generation is documented as supported only in Chrome headless. Confirm that your launch configuration and browser installation meet that requirement.
  • Check the destination: because paths are resolved to full paths, verify the process working directory when using a relative path. Use an absolute path and confirm the process can write to its parent directory.
  • Await the operation: do not start file-reading or upload work until PdfAsync has completed successfully.

The PDF is blank or missing content

  • Verify that navigation or SetContentAsync completed before PDF generation.
  • If the page fills in after the initial load, wait for the content your application relies on before printing.
  • Check whether the required images, stylesheets, or fonts are reachable from the browser and have loaded.
  • Inspect print-specific CSS. If you need screen styling, call EmulateMediaTypeAsync(MediaType.Screen) before printing.

Colors, backgrounds, or pagination look wrong

  • Enable background printing if the page relies on background graphics.
  • Review paper size, orientation, margins, scale, and page-range settings together; a change in one can shift content or alter page breaks.
  • Check @page rules and the option that controls whether CSS page size takes priority.
  • For custom headers or footers, ensure the configured margins leave room for them.

Tagged output is not available

The documented Tagged option has an old-headless-mode limitation. Verify the behavior against the Chromium and PuppeteerSharp versions deployed in your environment before relying on it.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Performance, reliability, and cost considerations

The cited PuppeteerSharp API and examples do not provide performance benchmarks, production reliability figures, or a cost comparison between file, byte-array, and stream output. Avoid choosing an output method based on an assumed speed advantage. Instead, choose the form that fits the next step in your application and measure your own workload if throughput or latency is important.

For a reliable capture flow, make browser and page lifetimes explicit, await navigation and PDF generation, choose a deterministic destination, and handle failures around browser startup, page loading, and file writing. If a remote browser is involved, account for that connection and deployment in your own system design; the example pattern does not establish a provider-specific guarantee.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Best Value
Sale
Sceptre New 22-Inch Gaming Monitor, FHD 1080p, Up to 144Hz, HDMI, DisplayPort, Built-in Speakers, Machine Black (E225W-FW144 Series, 2026)
  • 【INTEGRATED SPEAKERS】Whether you're at work or in the midst of an intense gaming session, our built-in speakers provide rich and seamless audio, all while keeping your desk clutter-free.
  • 【EASY ON THE EYES】 Protect your eyes and enhance your comfort with Blue-Light Shift technology. This feature reduces harmful blue light emissions from your screen, helping to alleviate eye strain during long hours of use and promoting healthier viewing habits.
  • 【WIDEN YOUR PERSPECTIVE】Our sleek minimal bezel design ensures undivided attention. The nearly bezel-free display seamlessly connects in a dual monitor arrangement, delivering an unobstructed view that lets you focus on more at once, completely distraction-free.

Or skip the browser setup

If you need a clean screenshot of a live URL rather than a PuppeteerSharp-controlled PDF workflow, ScreenshotNeo offers a website screenshot API and MCP server. A single GET request can return a screenshot or PDF. It is not a substitute for custom HTML via SetContentAsync or for PuppeteerSharp’s full browser layout controls.

curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp

See the ScreenshotNeo API documentation for request details. Before capture, it accepts the cookie or consent banner as a visitor and removes more than 60 known consent platforms, newsletter popups, and chat widgets; each of those steps can be turned off. Bot checks or CAPTCHAs, blank pages, timeouts, failed loads, and cache hits are not billed, and responses include X-Page-Verdict and X-Billed headers. Its MCP server provides take_screenshot, get_page_info, and capture_pdf tools for Claude, Cursor, and other MCP clients. The Free plan includes 1,000 shots per month without a card; paid plans start at $5 for 3,000 shots. Every feature is available on every plan.

Sign up for ScreenshotNeo’s free plan: 1,000 screenshots a month, no card required.

Frequently Asked Questions

Does PuppeteerSharp PDF generation work with every .NET target framework?

The documentation cited here does not establish universal target-framework compatibility. Check the requirements for the PuppeteerSharp package version and framework used by your project.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Leave a Reply

Your email address will not be published. Required fields are marked *

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Read next

Recommended PC Tool
Recommended PC Tool
PC Slower Than It Used to Be?Free scan - under a minute
Outdated Drivers Are Slowing You DownFree scan - exact matches

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.