---
title: "Convert a webpage URL to PDF in C#"
url: https://recursiveai.org/onerender/cookbook/convert-url-to-pdf/
description: "Fetch a known HTTPS webpage with HttpClient, resolve its CSS and image URLs after redirects, and save a PDF in C# without running JavaScript."
version: "1.4.0"
---

# Convert a webpage URL to PDF in C#

**OneRender** is a free, open-source HTML and CSS rendering library for .NET from Recursive AI. MIT or Apache-2.0, no native dependencies.

[NuGet](https://www.nuget.org/packages/RecursiveAI.OneRender.Pdf) · [GitHub](https://github.com/recursive-ai-oss/onerender-csharp) · [Docs](https://recursiveai.org/onerender/docs/) · [Download example (.zip)](https://recursiveai.org/onerender/cookbook/convert-url-to-pdf/convert-url-to-pdf.zip)

Fetch with `HttpClient`, then render the HTML with `HtmlPdf.ToPdf`.

OneRender doesn’t download CSS or images itself: [list the files your page references](#how-do-i-keep-the-css-and-images-when-converting-a-webpage-to-pdf) (`card.css` and `tile.png` in the sample), or the PDF will be missing those styles and images. If JavaScript builds the page or loads its content after it opens, the PDF won’t show that content, so use a server-rendered or print URL.

```shell
dotnet add package RecursiveAI.OneRender.Pdf
```

Requires [.NET 10](https://dotnet.microsoft.com/download/dotnet/10.0) (net10.0); .NET 9 and earlier aren’t supported.

```csharp
using OneRender.Pdf;

// Pass a known HTTPS page URL.
using var http = new HttpClient();
using var res = await http.GetAsync(args[0]);
res.EnsureSuccessStatusCode();
var final = res.RequestMessage!.RequestUri!;
var html = await res.Content
    .ReadAsStringAsync();

var assets = new Dictionary<string, byte[]>();
string[] names = ["card.css", "tile.png"];
foreach (var name in names)
{
    var url = new Uri(final, name);
    assets[url.AbsoluteUri] =
        await http.GetByteArrayAsync(url);
}
var options = new HtmlPdfOptions
{
    BaseUrl = final.AbsoluteUri,
    Resources = assets.GetValueOrDefault
};
var pdf = HtmlPdf.ToPdf(html, options);
File.WriteAllBytes("webpage.pdf", pdf);
Console.WriteLine("Wrote webpage.pdf");
```

[The example](https://recursiveai.org/onerender/cookbook/convert-url-to-pdf/convert-url-to-pdf.zip) is the full program below: unzip it and `dotnet run`.

Writes `webpage.pdf` and prints `Wrote webpage.pdf`. To use the snippet in a new console project, pass a known HTTPS URL with `dotnet run -- <url>` and replace the two asset names with the files your page references. The download runs without arguments and serves its own sample over HTTPS.

## The full program

```csharp
using OneRender.Pdf;

await using var fixture = args.Length == 0 ? await Fixture.StartAsync() : null;
Uri start = fixture?.StartUrl ?? new Uri(args[0]);
if (start.Scheme != Uri.UriSchemeHttps)
    throw new ArgumentException("Pass a known HTTPS page URL.");
using var http = fixture?.CreateClient() ?? new HttpClient();
using var response = await http.GetAsync(start);
response.EnsureSuccessStatusCode();
var final = response.RequestMessage!.RequestUri!;
var html = await response.Content.ReadAsStringAsync();

var assets = new Dictionary<string, byte[]>();
foreach (var name in new[] { "card.css", "tile.png" })
{
    var url = new Uri(final, name);
    assets[url.AbsoluteUri] = await http.GetByteArrayAsync(url);
}

using var output = File.Create("webpage.pdf");
var result = HtmlPdf.ToPdf(html, output, new HtmlPdfOptions
{
    BaseUrl = final.AbsoluteUri,
    Resources = url => assets.GetValueOrDefault(url)
});
Console.WriteLine($"Fetched {final.AbsolutePath}");
Console.WriteLine($"webpage.pdf: {result.PageCount} page(s)");
foreach (var diagnostic in result.Diagnostics)
    Console.WriteLine(diagnostic.Message);
```

`dotnet run` prints:

```text
Fetched /docs/card.html
webpage.pdf: 1 page(s)
```

The download’s `Fixture.cs` redirects `/start` to `/docs/card.html`. The destination serves this HTML:

```html
<!doctype html>
<link rel="stylesheet" href="card.css">
<h1>Workshop schedule</h1>
<img src="tile.png" width="32" height="32" alt="Blue square">
```

`card.css` contains `h1 { color: #16407a; }`, and `tile.png` is a 32 × 32 blue square. Both are served under `/docs/`. The example starts and stops the HTTPS server itself; it trusts the fixture certificate only for the client used in the example. Passing your own HTTPS URL uses the normal `HttpClient` certificate checks instead.

If the page or either named asset returns an HTTP error, the fetch throws before the program opens `webpage.pdf` for writing. Once rendering begins, the stream overload returns a page count and diagnostics, which the example prints if there are any.

## Variations

**Set the paper size to US Letter.** Add this property to the `HtmlPdfOptions` initializer:

```csharp
Page = PdfPageSetup.Letter,
```

## Related recipes

- [Convert a local HTML file to PDF](https://recursiveai.org/onerender/cookbook/html-to-pdf/)
- [Load local CSS and images for HTML to PDF](https://recursiveai.org/onerender/cookbook/load-html-render-resources/)
- [Inspect HTML-to-PDF diagnostics](https://recursiveai.org/onerender/cookbook/inspect-html-to-pdf-diagnostics/)

---

## The short answer

To convert a webpage URL to PDF in C#, fetch the HTML with `HttpClient`, read the final URL from `response.RequestMessage.RequestUri`, and pass that URL as `HtmlPdfOptions.BaseUrl`. Download the resources you intend to include before you call `HtmlPdf.ToPdf`. The renderer gets them from your `Resources` callback, not from the network.

## How do I convert a webpage to PDF after a redirect?

Resolve relative resource names from the URL that delivered the HTML. In this example `/start` redirects to `/docs/card.html`. The HTML references `card.css`, which belongs at `/docs/card.css`. Resolving it against `/start` would send the asset request to `/card.css` instead. Keeping the same final URL for both the download step and `BaseUrl` makes the renderer ask for the same absolute address you put in the dictionary.

## How do I keep the CSS and images when converting a webpage to PDF?

Fetch the known CSS and image URLs and store the actual bytes under their resolved absolute addresses. In `Resources`, return those bytes only when the requested address is in the dictionary. If the page uses a separate font or a stylesheet references a background image, include that asset too, using the address the renderer resolves for it. This example doesn’t crawl the document for dependencies: the short list is explicit because the input is known.

## Can I convert any webpage into a PDF without a browser?

This method is for pages whose HTTP response already contains the content you want printed. It lays out the supplied markup and styles; it doesn’t run a script that fetches rows for a table, opens an accordion, or fills an empty page shell. For a page you control, use a server-rendered HTML or print route that includes the final content in its response. A page that needs sign-in also needs an appropriately authenticated fetch before the renderer can see the intended HTML.
