How to generate a PDF from HTML using wkhtmltopdf in C#
By FoxLearn 2/17/2025 7:27:07 AM 112
To convert an HTML file into a PDF in a C# Windows Forms application, we will use Pechkin the .NET wrapper for the wkhtmltopdf DLL. Pechkin uses the Webkit engine to convert HTML to PDF. It can be installed as a NuGet package.
For most applications, SynchronizedPechkin is recommended to prevent crashes when working with multi-threaded code. However, for simpler, single-threaded tasks, SimplePechkin may be sufficient.
To install the package:
- Right-click on your project in Solution Explorer and select Manage NuGet Packages.
- In the search bar, type Pechkin.Synchronized and install it.
Once installed, you're ready to use Pechkin in your project.
Generate a PDF
The Convert
method in Pechkin takes an HTML string (or a configuration object) and converts it to a PDF. It returns a byte array containing the binary PDF data.
Generate a Simple PDF from an HTML String
You can quickly create a PDF by using a basic configuration object.
using System; using Pechkin; class Program { static void Main() { // Create a new global configuration for wkhtmltopdf GlobalConfig gc = new GlobalConfig(); // Create a SimplePechkin converter with the global configuration SimplePechkin pechkin = new SimplePechkin(gc); // HTML content to convert into PDF string htmlContent = "<html><body><h1>Hello, World!</h1><p>This is a test PDF.</p></body></html>"; // Convert the HTML content into PDF (byte array) byte[] pdfContent = pechkin.Convert(htmlContent); // Save the PDF to a file SavePdfToFile("output.pdf", pdfContent); } // Method to save the byte array to a PDF file static void SavePdfToFile(string filePath, byte[] pdfContent) { try { // Write the PDF content to a file System.IO.File.WriteAllBytes(filePath, pdfContent); Console.WriteLine("PDF successfully created at " + filePath); } catch (Exception ex) { Console.WriteLine("Error while saving PDF: " + ex.Message); } } }
In this example:
- GlobalConfig: Configures the settings for the PDF generation (e.g., paper size, margins, etc.).
- SimplePechkin: A lightweight version of Pechkin that directly converts HTML to PDF.
- The Convert method takes an HTML string and returns the generated PDF as a byte array.
- The SavePdfToFile method saves the PDF byte array to a file using System.IO.File.WriteAllBytes.
Generate PDF from Website URL
If you want to generate a PDF from a website, you can pass the URL to the SetPageUri method in the ObjectConfig.
using System; using Pechkin.Synchronized; class Program { static void Main() { // Create a new global configuration for wkhtmltopdf GlobalConfig gc = new GlobalConfig(); // Set some optional configurations, such as margins and paper size gc.SetMargins(new System.Drawing.Printing.Margins(50, 50, 50, 50)) .SetDocumentTitle("Website PDF") .SetPaperSize(System.Drawing.Printing.PaperKind.Letter); // Create an IPechkin converter with synchronized options IPechkin pechkin = new SynchronizedPechkin(gc); // Create a document configuration object ObjectConfig config = new ObjectConfig(); config.SetPageUri("http://example.com"); // Website URL to convert to PDF // Convert the website to a PDF byte[] pdfContent = pechkin.Convert(config); // Save the generated PDF SavePdfToFile("website_output.pdf", pdfContent); } static void SavePdfToFile(string filePath, byte[] pdfContent) { try { // Save the PDF content to a file System.IO.File.WriteAllBytes(filePath, pdfContent); Console.WriteLine("PDF successfully created at " + filePath); } catch (Exception ex) { Console.WriteLine("Error while saving PDF: " + ex.Message); } } }
In this example:
- SetPageUri: This method is used to specify the URL of the website you want to convert into a PDF.
- The rest of the code is similar to the previous example, except this time you're passing a website URL instead of HTML content.
Generate a PDF from a Local HTML File
To generate a PDF from a local HTML file, use the SetPageUri method with a file:/// URL.
using System; using Pechkin.Synchronized; class Program { static void Main() { // Create global configuration object GlobalConfig gc = new GlobalConfig(); gc.SetMargins(new System.Drawing.Printing.Margins(50, 50, 50, 50)) .SetDocumentTitle("Local HTML PDF") .SetPaperSize(System.Drawing.Printing.PaperKind.Letter); // Create IPechkin converter IPechkin pechkin = new SynchronizedPechkin(gc); // Set path to local HTML file string htmlFilePath = @"C:/path/to/your/file.html"; // Adjust path accordingly ObjectConfig config = new ObjectConfig(); config.SetPageUri("file:///" + htmlFilePath); // Prefix the path with 'file:///' // Convert the local HTML file to PDF byte[] pdfContent = pechkin.Convert(config); // Save the generated PDF SavePdfToFile("local_file_output.pdf", pdfContent); } static void SavePdfToFile(string filePath, byte[] pdfContent) { try { // Write PDF to file System.IO.File.WriteAllBytes(filePath, pdfContent); Console.WriteLine("PDF successfully created at " + filePath); } catch (Exception ex) { Console.WriteLine("Error while saving PDF: " + ex.Message); } } }
In this example:
- The
file:///
prefix is required when providing the path to a local HTML file.
Using Pechkin and wkhtmltopdf, you can easily generate PDFs from HTML content in your C# applications.
- Using the OrderBy and OrderByDescending in LINQ
- Querying with LINQ
- Optimizing Performance with Compiled Queries in LINQ
- MinBy() and MaxBy() Extension Methods in .NET
- SortBy, FilterBy, and CombineBy in NET 9
- Exploring Hybrid Caching in .NET 9.0
- Using Entity Framework with IDbContext in .NET 9.0
- Primitive types in C#