What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

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

Some links on this page are affiliate links: if you buy through them we may earn a commission, at no extra cost to you.

Install the HtmlRenderer.PdfSharp NuGet package, pass your HTML string and a PDFsharp page size to PdfGenerator.GeneratePdf, then save the returned PdfDocument. Use PdfGenerateConfig when you need custom margins, orientation, or other page settings. The package is a PDFsharp integration—not a feature built into PDFsharp itself.

Minimal HTML-to-PDF conversion

Create a .NET console, web, or worker project and add HtmlRenderer.PdfSharp. The NuGet page displayed version 1.6.1 when this article was prepared; package versions change, so confirm the current version before pinning it.

<PackageReference Include='HtmlRenderer.PdfSharp' Version='1.6.1' />

The documented quick-start pattern is:

using PdfSharp;
using PdfSharp.Pdf;
using TheArtOfDev.HtmlRenderer.PdfSharp;

string html = "<p><h1>Hello World</h1>This is html rendered text</p>";

PdfDocument pdf = PdfGenerator.GeneratePdf(html, PageSize.A4);
pdf.Save("output.pdf");

GeneratePdf returns a PDFsharp PdfDocument. The final Save call writes that document to a file; choose a stream instead when returning the PDF from an HTTP endpoint.

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

What the package does—and what PDFsharp does not

PDFsharp is the PDF library. Its own FAQ identifies HTML Renderer for PDF using PDFsharp as the third-party layer that turns HTML into PDF. Installing PDFsharp alone does not give you an HTML converter.

HTML Renderer describes the renderer as a managed C# implementation with stated support for HTML 4.01 and CSS level 2, including malformed real-world HTML. Those are project capabilities, not a guarantee that every browser-era HTML or CSS feature will match Chrome or Firefox. Test the actual templates, fonts, images, and page breaks used by your application.

Set page size, orientation, and margins

The simple overload accepts an HTML string and a PageSize. For layout control, use the overload that accepts PdfGenerateConfig. The configuration class exposes page-size and orientation properties, individual edge margins, and SetMargins for assigning one value to all four edges.

using PdfSharp;
using PdfSharp.Pdf;
using TheArtOfDev.HtmlRenderer.PdfSharp;

string html = @"
  <html>
    <body>
      <h1>Invoice</h1>
      <p>Rendered with a custom page configuration.</p>
    </body>
  </html>";

var config = new PdfGenerateConfig
{
    PageSize = PageSize.Letter,
    Landscape = false,
    MarginTop = 36,
    MarginBottom = 36,
    MarginLeft = 42,
    MarginRight = 42
};

PdfDocument pdf = PdfGenerator.GeneratePdf(html, config);
pdf.Save("invoice.pdf");

Margin values are PDFsharp units. PdfGenerateConfig also provides conversion helpers for millimetres or inches, which is safer than scattering unit conversions through your code. Check the members in the version you install because APIs can evolve.

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

Choosing a page size

  • Use PageSize.A4 for the common international office format.
  • Use PageSize.Letter for US letter documents.
  • Set Landscape = true for wide tables, charts, or reports.
  • Use explicit edge margins when a header, footer, table, or signature requires predictable printable space.

Complete example with reusable conversion code

Keeping conversion in a method makes it easier to test templates and send output to a file or stream later.

using PdfSharp;
using PdfSharp.Pdf;
using TheArtOfDev.HtmlRenderer.PdfSharp;

static PdfDocument ConvertHtml(string html, bool landscape)
{
    var config = new PdfGenerateConfig
    {
        PageSize = PageSize.A4,
        Landscape = landscape,
        MarginTop = 32,
        MarginBottom = 32,
        MarginLeft = 32,
        MarginRight = 32
    };

    return PdfGenerator.GeneratePdf(html, config);
}

string documentHtml = @"
<!doctype html>
<html>
  <head>
    <meta charset='utf-8'>
    <style>
      body { font-family: Arial, sans-serif; color: #222; }
      h1 { color: #174a7e; }
      .total { font-weight: bold; border-top: 1px solid #999; }
    </style>
  </head>
  <body>
    <h1>Monthly report</h1>
    <p>This HTML becomes a PDF document.</p>
    <p class='total'>Total: $125.00</p>
  </body>
</html>";

using PdfDocument pdf = ConvertHtml(documentHtml, landscape: false);
pdf.Save("report.pdf");

For an ASP.NET response, save to a MemoryStream, reset its position to zero, and return the bytes with application/pdf. Dispose the document and stream according to the lifetime rules of your application.

External CSS, images, and resource loading

HTML that references external stylesheets or images needs resource loading that works in your deployment environment. The PdfGenerator API exposes optional stylesheet and image-load event handlers on its overloads. Use those hooks when you need to control how a stylesheet or image is fetched, translated, or supplied from application storage.

  • Prefer absolute, reachable URLs or embed resources when a template is rendered outside the browser that normally serves it.
  • Confirm that the process can access private files, certificates, proxies, and authentication required by your assets.
  • Use supported image formats and verify that the process has permission to read local files.
  • Keep a fallback style sheet for important print rules; browser-only CSS may not be understood by this renderer.

Do not assume JavaScript will run as it does in a browser. This library is documented around HTML 4.01 and CSS level 2 rather than a complete browser engine. If a page depends on client-side rendering, fetch the final data first and generate static HTML for the renderer.

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

Append pages to an existing PDF

Besides creating a new document, the same source provides AddPdfPages overloads for appending rendered HTML pages to an existing PDFsharp document. This is useful for combining several independently generated sections while retaining one output file. Choose the overload that matches your page configuration and resource-loading needs, then save the completed PdfDocument once.

Package targets and compatibility

The repository project file declares targets netstandard2.0 and net8.0 and references PDFsharp. These are targets declared by that project, not a promise that every runtime, operating system, or deployment combination has identical behavior. Verify the package’s dependency graph and run your own representative documents on the runtime you deploy.

Production workflow

  1. Make the HTML deterministic. Resolve template data, dates, numbers, and localization before calling the renderer.
  2. Choose page settings. Select A4 or Letter, decide portrait or landscape, and set margins with PdfGenerateConfig.
  3. Prepare resources. Make CSS, images, and fonts available to the rendering process; use the documented loading hooks where necessary.
  4. Render and save. Capture the returned PdfDocument to a file, stream, or HTTP response.
  5. Validate the result. Open PDFs produced from long text, tables, images, special characters, and page breaks. Compare them with your acceptance criteria rather than assuming browser parity.
  6. Monitor failures. Log the input template identifier, page configuration, resource errors, and output path without logging sensitive document contents.

Troubleshooting common failures

Symptom Likely cause Fix
Compiler cannot find PdfGenerator Package or namespace is missing. Install HtmlRenderer.PdfSharp and import TheArtOfDev.HtmlRenderer.PdfSharp. Restore packages and rebuild.
Compiler cannot find PageSize or PdfDocument PDFsharp namespaces are absent or dependency versions conflict. Add using PdfSharp; and using PdfSharp.Pdf;; inspect resolved package versions and follow the installed package’s dependency requirements.
Output is blank or missing an image The resource URL or local path is unavailable to the renderer. Use a reachable or embedded resource, check process permissions and authentication, and handle image loading through the available event hook.
CSS looks different from the browser The renderer’s stated scope is HTML 4.01 and CSS level 2, not a full browser engine. Reduce browser-specific CSS, add simpler print styles, and validate the exact markup you ship.
Text or tables run off the page Content exceeds the selected page width, margins are too large, or a wide table needs landscape mode. Adjust margins, choose landscape orientation, constrain table widths, or split the content into sections.
Special characters render incorrectly Encoding or font availability is inconsistent. Declare the document charset, use fonts available to the process, and test the actual language and symbols in your output.
Pages differ between machines Different package, PDFsharp, runtime, fonts, or resource responses. Pin compatible package versions, deploy required fonts and assets, and compare generated PDFs in the same environment used in production.

Performance, reliability, and cost considerations

HtmlRenderer.PdfSharp runs in your .NET process, so there is no per-document SaaS charge. Your costs are the compute, memory, storage, and operational work of the application and its PDFsharp dependencies. Rendering time and memory depend on HTML size, image dimensions, font usage, and the number of pages; the available project material does not establish a universal benchmark.

For reliable batch work, reuse templates, resize unnecessarily large images before rendering, avoid unbounded HTML input, and process very large jobs with an explicit queue or timeout. Keep output validation in your deployment tests because a successful method call does not prove that every visual requirement was met.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Or skip the browser setup

If your source is a live website rather than an HTML string, ScreenshotNeo can return a clean screenshot or PDF through one GET request. It accepts the cookie or consent banner like a visitor, removes more than 60 known consent platforms plus newsletter popups and chat widgets, and bills only clean shots. Bot checks, CAPTCHAs, blank pages, timeouts, failed loads, and cache hits cost nothing, with the result identified by X-Page-Verdict and X-Billed headers. An MCP server supplies take_screenshot, get_page_info, and capture_pdf tools to Claude, Cursor, and other MCP clients.

For a direct request, see the ScreenshotNeo documentation and use your access key:

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

The same call from Python is:

import requests
r = requests.get('https://api.screenshotneo.com/v1/shot', params={'access_key': 'YOUR_API_KEY', 'url': 'https://stripe.com'}, timeout=90)
open('shot.webp', 'wb').write(r.content)

And in Node.js:

const q = new URLSearchParams({ access_key: 'YOUR_API_KEY', url: 'https://stripe.com' });
const res = await fetch(`https://api.screenshotneo.com/v1/shot?${q}`);

ScreenshotNeo has a free allowance of 1,000 shots per month with no card; paid plans start at $5 for 3,000 shots. Every feature is included on every plan, and yearly billing provides two months free. Create a free ScreenshotNeo account to try it.

Frequently Asked Questions

Is HtmlRenderer.PdfSharp a browser engine?

No. Its project metadata states support for HTML 4.01 and CSS level 2. Treat browser-only behavior as unverified and test your own templates.

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

Can I use PDFsharp without HtmlRenderer.PdfSharp to convert HTML?

No. PDFsharp supplies PDF creation; the HTML Renderer integration provides the HTML-to-PDF layer.

Where should page margins be configured?

Use the PdfGenerateConfig overload and set its edge properties or call SetMargins; the simple PageSize overload is intended for basic conversions.

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.