Recursive AI

Download and open a PDF from a URL in C#

OnePDF is a free, open-source PDF library for .NET from Recursive AI. MIT or Apache-2.0, no native dependencies.

Terminal
dotnet add package RecursiveAI.OnePdf

Requires .NET 10 (net10.0); .NET 9 and earlier aren’t supported.

C#
using OnePdf;
 
// Pass a PDF URL as the first argument.
using var client = new HttpClient();
await using var body =
    await client.GetStreamAsync(args[0]);
using var doc =
    await PdfDocument.OpenAsync(body);
Console.WriteLine($"Pages: {doc.Pages.Count}");

The example is the full program below: unzip it and dotnet run. To run only the code above, paste it into Program.cs of a new dotnet new console project and dotnet run.

To run the snippet at the top, pass a direct PDF URL, such as this one-page sample from W3C:

Terminal
dotnet run -- https://www.w3.org/WAI/ER/tests/xhtml/testfiles/resources/pdf/dummy.pdf

It opens the PDF without writing a local file and prints:

Text
Pages: 1

To save the PDF to disk instead, see Variations.

The full program

The download defaults to the W3C sample and applies a deadline to the request and response-body read. It needs internet access but no API key.

C#
using OnePdf;
 
const string sampleUrl = "https://www.w3.org/WAI/ER/tests/xhtml/testfiles/resources/pdf/dummy.pdf";
string url = args.Length > 0 ? args[0] : sampleUrl;
using var client = new HttpClient();
using var deadline = new CancellationTokenSource(TimeSpan.FromSeconds(30));
using var response = await client.GetAsync(url,
    HttpCompletionOption.ResponseHeadersRead, deadline.Token);
response.EnsureSuccessStatusCode();
 
await using var body = await response.Content.ReadAsStreamAsync(deadline.Token);
using var doc = await PdfDocument.OpenAsync(body, cancellationToken: deadline.Token);
Console.WriteLine($"Pages: {doc.Pages.Count}");

Both GetStreamAsync and the full program’s EnsureSuccessStatusCode throw HttpRequestException on a non-success HTTP status; if a successful response isn’t a readable PDF, OpenAsync can throw PdfException instead.

Variations

Save the PDF instead of opening it

Replace the line that opens the document and the page-count line in the snippet with this code. Run it with the same PDF URL. It writes download.pdf, replacing an existing file of that name.

C#
// body is the HTTP response stream from above.
await using var file = File.Create("download.pdf");
await body.CopyToAsync(file);

The short answer

Request the direct PDF URL with HttpClient, check the HTTP status, and pass the response stream to PdfDocument.OpenAsync. If you only need a file on disk, copy the response stream to a file instead; that part doesn’t need OnePDF.

How do I download a PDF from a URL?

Use the address that sends the PDF bytes. Check the response status before opening the body so a missing file or permission error doesn’t get reported as a PDF parsing problem. A successful status isn’t proof that the response is a PDF: a sign-in page or an HTML preview can return a successful status too. If that happens, look for the download link or use the PDF endpoint documented by the site.

Saving an existing PDF and generating a PDF from a web page are different tasks. Copying the bytes of an HTML response to a filename ending in .pdf still leaves you with HTML. To turn a web page into a PDF, first render it with a tool that supports browser printing or HTML-to-PDF conversion. You don’t need that step when the server already sends a PDF.

How do I download a file from a URL without buffering the whole response?

Use GetStreamAsync and copy the body to a file as in the variation. It returns a stream without first buffering the whole body. The full program uses ResponseHeadersRead to get the same behavior while keeping the response object available. Keep the network stream open until the copy finishes. If you only need the file, there’s no reason to parse the PDF during the download.

Opening the response directly is different. OpenAsync reads a non-seekable stream into memory so OnePDF can read the document. If the PDF is large, it’s better to stream it to disk and open the saved path. For a service, set a download size policy separately from the parser’s limits. A deadline caps how long you wait for the body, not how many bytes can arrive before then.

How do I download a PDF from an API?

Use the endpoint that returns the PDF bytes and apply the API’s documented authentication to the HTTP request. OnePDF opens the response body, not the URL, and doesn’t handle HTTP authentication for you. If the API returns JSON with a download link, fetch that link separately before opening the PDF. Sending the JSON body straight to OpenAsync won’t open the document.

When reading the body with ResponseHeadersRead, give that read its own cancellation deadline or pass the same token through both steps, as the full program does. The client’s timeout on the headers-only request doesn’t by itself cover the later body read.

All onepdf recipes