This step-by-step tutorial shows how to generate PDF files in C# with DotNetBrowser.
There are many PDF libraries in the .NET world. But we find it easier to generate PDFs with an integrated browser. Since DotNetBrowser can work entirely off the screen, you can use it on servers, both on Windows and Linux.
The algorithm is simple:
- Load a page.
- Fill the page with data.
- Configure the printer.
- Print the page as PDF.
Step 1: Create a project
For our task, we don’t need the user interface. Therefore, we create a console application.
Open the Terminal or Command Line prompt, navigate to the necessary directory, and run the following command:
dotnet new console -o PdfGeneration
Step 2: Integrate DotNetBrowser
Change the directory to PdfGeneration
and add the DotNetBrowser package from
NuGet:
# For Windows:
dotnet add package DotNetBrowser
# For other platforms:
dotnet add package DotNetBrowser.Linux-x64
dotnet add package DotNetBrowser.Linux-arm64
dotnet add package DotNetBrowser.macOS-x64
dotnet add package DotNetBrowser.macOS-arm64
After that, get your free license to start using DotNetBrowser.
Step 3: Load the page
Create a simple console application that starts DotNetBrowser and loads the page with the template:
class Program
{
private static async Task Main()
{
var options = new EngineOptions.Builder
{
RenderingMode = RenderingMode.OffScreen,
LicenseKey = "your license key"
}.Build();
using var engine = EngineFactory.Create(engineOptions);
using var browser = engine.CreateBrowser();
// The page is a resource in the project.
var pageUrl = Path.GetFullPath("template.html");
await browser.Navigation.LoadUrl(pageUrl);
}
}
This is a regular page in a regular browser. Thus, use any JavaScript library (e.g. plotly.js or D3.js), WebGL, SVG graphics, or any other technology available in Chromium.
Step 4: Fill the page with data
To fill page with data, use DOM API or execute any JavaScript code. Let’s use a couple of JavaScript functions that we embedded into the page:
private static void FillInData(IBrowser browser)
{
var accountNumber = "123-4567";
var name = "Dr. Emmett Brown";
var address = "1640 Riverside Drive";
var reportingPeriod = "Oct 25 — November 25, 1985";
browser.MainFrame.ExecuteJavaScript(
$"setBillInfo('{accountNumber}', '{name}', '{address}', '{reportingPeriod}')"
);
var dayCost = 500; // Dollars.
var dayUsage = 1.21; // Gigawatts.
var nightCost = 312;
var nightUsage = 88;
browser.MainFrame.ExecuteJavaScript(
$"addCharge('Day Tariff', {dayUsage}, {dayCost});" +
$"addCharge('Night Tariff', {nightUsage}, {nightCost});"
);
}
Step 5: Configure printing
Tell the browser to print automatically and configure the print settings:
private static TaskCompletionSource<string> ConfigurePrinting(IBrowser browser)
{
// Tell the browser to print automatically instead of showing the print preview.
browser.RequestPrintHandler =
new Handler<RequestPrintParameters, RequestPrintResponse>(
p => RequestPrintResponse.Print()
);
TaskCompletionSource<string> whenCompleted = new();
// When the browser prints an HTML page.
browser.PrintHtmlContentHandler =
new Handler<PrintHtmlContentParameters, PrintHtmlContentResponse>(
parameters =>
{
// Use the PDF printer.
var printer = parameters.Printers.Pdf;
var job = printer.PrintJob;
// Generate a random name for PDF file.
var guid = Guid.NewGuid().ToString();
var path = Path.GetFullPath($"{guid}.pdf");
job.Settings.PdfFilePath = path;
// Remove white areas on the sides.
job.Settings.PageMargins = PageMargins.None;
// Remove default browser headers and footers.
job.Settings.PrintingHeaderFooterEnabled = false;
job.PrintCompleted += (_, _) => whenCompleted.SetResult(path);
// Proceed with printing.
return PrintHtmlContentResponse.Print(printer);
});
return whenCompleted;
}
Step 6: Generate PDF file
Put it all together, start printing, and wait until it’s finished:
private static async Task Main()
{
var engineOptions = new EngineOptions.Builder
{
RenderingMode = RenderingMode.OffScreen,
LicenseKey = "your license key"
}.Build();
using var engine = EngineFactory.Create(engineOptions);
using var browser = engine.CreateBrowser();
await browser.Navigation.LoadUrl(Path.GetFullPath("template.html"));
FillInData(browser);
var whenPrintCompleted = ConfigurePrinting(browser);
browser.MainFrame.Print();
var resultPath = await whenPrintCompleted.Task;
}
Results
Run the program:
dotnet run
And open the generated PDF file:
Source code
You can find the source code of this application in our GitHub repository.
Discover more
- Choosing between DotNetBrowser and WebView2
- Choosing between DotNetBrowser and CefSharp
- Chrome extensions in DotNetBrowser