Recursive AI

Batch convert a folder of HTML files to PDF in C#

OnePdf.Html is a free, open-source .NET library from Recursive AI that converts PDF to HTML and HTML to PDF. MIT or Apache-2.0, no native dependencies.

Use ConvertFiles for one PDF per HTML file. No JavaScript runs.

Terminal
dotnet add package RecursiveAI.OnePdf.Html.Render

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

C#
using OnePdf.Html.Render;
 
var files = Directory.GetFiles(
    "html", "*.html");
var batch = HtmlToPdf.ConvertFiles(
    files, "pdf");
var saved = batch.Count(item => item.Succeeded);
Console.WriteLine(
    $"Saved {saved}/{batch.Count} PDFs");
return saved == batch.Count ? 0 : 1;

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.

With the two samples, the snippet prints:

Text
Saved 2/2 PDFs

The download includes both HTML files. For the snippet, create a folder named html beside Program.cs. Save these files there:

january.html

HTML
<!doctype html>
<html lang="en">
<title>January report</title>
<h1>January report</h1>
<p>Orders: 42.</p>

february.html

HTML
<!doctype html>
<html lang="en">
<title>February report</title>
<h1>February report</h1>
<p>Orders: 57.</p>

The full program

The downloaded program sorts the paths, prints one result per file, and exits with code 1 if any file failed. The converter creates the pdf folder if needed. Use a fresh output folder if you want to keep PDFs from an earlier run.

C#
using OnePdf.Html.Render;
 
var files = Directory
    .GetFiles("html", "*.html")
    .OrderBy(path => path, StringComparer.Ordinal);
var batch = HtmlToPdf.ConvertFiles(files, "pdf");
foreach (var item in batch)
{
    if (item.Result is { } pdf)
    {
        var name = Path.GetFileName(item.OutputPath);
        Console.WriteLine($"{name}: {pdf.PageCount} page(s)");
    }
    else
    {
        Console.Error.WriteLine(
            $"{item.InputPath}: {item.Error!.Message}");
        Environment.ExitCode = 1;
    }
}

dotnet run prints:

Text
february.pdf: 1 page(s)
january.pdf: 1 page(s)

If a listed HTML file can’t be read, its batch item has an error; the other files can still convert.

Variations

Include subfolders and run at most two conversions at a time. Replace the file search, sort and ConvertFiles call in the full program with:

C#
var files = Directory.GetFiles(
    "html", "*.html", SearchOption.AllDirectories)
    .OrderBy(path => path, StringComparer.Ordinal);
var options = new HtmlToPdfOptions
{
    MaxDegreeOfParallelism = 2,
};
var batch = HtmlToPdf.ConvertFiles(files, "pdf", options);

If you copy html/january.html to html/archive/january.html before running this variation, both inputs get a PDF: january.pdf and january-2.pdf.

The short answer

Use Directory.GetFiles to select local HTML files, then pass the paths and the output folder to HtmlToPdf.ConvertFiles. For the two sample files, the result is pdf/february.pdf and pdf/january.pdf. This is one PDF per HTML file, not one combined document. The converter opens each HTML file directly; there’s no need to read every file into a string first.

How do I batch convert HTML files in subfolders?

Use SearchOption.AllDirectories in Directory.GetFiles, as in the variation. The first snippet deliberately searches just the top level. Its *.html filter does not select *.htm files; pass a list that includes those paths if you need to convert both extensions.

The PDF output goes to one folder even if your inputs are spread across several. Relative references to local stylesheets, images, and fonts can still resolve from each HTML file’s own folder. Keep an input’s assets with it rather than gathering the HTML files in a new flat folder before conversion. See resource loading.

What happens if two HTML files have the same name?

The first input named january.html gets january.pdf; later inputs with that name get january-2.pdf, january-3.pdf, and so on. The suffix is based on the order of the paths you pass in, not on which conversion finishes first. Sort the paths before converting if you need the same naming and result order each time. The suffix rule resolves collisions inside the current batch. A successful conversion replaces an existing PDF of the same name in the output folder.

What happens if one file in a batch fails?

Check the returned items, not just whether the method returned. Each item corresponds to an input and carries its conversion result or an error, in input order. For a job that runs unattended, log the failed item’s InputPath and Error so you can retry just those files. The full example exits with code 1 if an item fails, while keeping the PDFs that were written for successful items.

All files in one call share the same options. Set MaxDegreeOfParallelism if you need to limit how many are in flight at once, especially when inputs contain large images. Without a setting, the converter runs at most four conversions at once or fewer if the processor count is lower. See the batch API.

All onepdf-html recipes