How to Convert HTML to PDF with SelectPdf Library for .NETConverting HTML to PDF is a common requirement for generating reports, invoices, receipts, documentation, or archived web pages. SelectPdf is a mature, feature-rich .NET library that simplifies HTML-to-PDF conversion and offers extensive control over rendering, styling, headers/footers, security, and performance. This guide covers installation, basic usage, advanced configuration, troubleshooting, and best practices so you can integrate SelectPdf into your .NET applications quickly and reliably.
What is SelectPdf?
SelectPdf is a commercial .NET library (with free community editions) that converts HTML, URLs, or raw HTML strings into PDF documents. It supports modern CSS and JavaScript, precise pagination, headers/footers, bookmarks, table-of-contents generation, PDF security, and PDF/A compliance. Because it renders HTML using an embedded engine, output closely matches what a browser would produce.
Prerequisites
- .NET environment (SelectPdf supports .NET Framework and .NET Core / .NET 5+).
- A development IDE (Visual Studio, VS Code, Rider).
- A SelectPdf license key for production use; you can use a trial or community edition for development and testing.
Installing SelectPdf
Install the SelectPdf package via NuGet. From the Package Manager Console:
Install-Package SelectPdf
Or using dotnet CLI:
dotnet add package SelectPdf
Add the using directive to your C# files:
using SelectPdf;
Basic HTML-to-PDF Conversion (Example)
This minimal example converts an HTML string into a PDF saved to disk.
using SelectPdf; using System; class Program { static void Main() { // Create a new HtmlToPdf converter HtmlToPdf converter = new HtmlToPdf(); // Optionally set converter options converter.Options.PdfPageSize = PdfPageSize.A4; converter.Options.PdfPageOrientation = PdfPageOrientation.Portrait; converter.Options.MarginTop = 20; converter.Options.MarginBottom = 20; converter.Options.MarginLeft = 20; converter.Options.MarginRight = 20; // HTML to convert string htmlString = "<html><body><h1>Hello, SelectPdf!</h1><p>This is a simple PDF.</p></body></html>"; // Convert HTML string to PDF document PdfDocument doc = converter.ConvertHtmlString(htmlString); // Save the PDF document string outputPath = "output.pdf"; doc.Save(outputPath); // Close the document to release resources doc.Close(); Console.WriteLine($"PDF saved to {outputPath}"); } }
Converting a URL to PDF
To convert a live webpage, use ConvertUrl:
HtmlToPdf converter = new HtmlToPdf(); PdfDocument doc = converter.ConvertUrl("https://example.com"); doc.Save("example.pdf"); doc.Close();
Notes:
- If the page requires authentication, you can use converter.Options.HttpRequestHeaders or other means to supply cookies/headers.
- For pages that load large external resources, increase timeout settings via converter.Options.MinPageLoadTime and converter.Options.MaxPageLoadTime.
Converting an HTML File
Load an HTML file from disk and convert:
string html = System.IO.File.ReadAllText("page.html"); HtmlToPdf converter = new HtmlToPdf(); PdfDocument doc = converter.ConvertHtmlString(html, "file:///C:/path/to/"); doc.Save("file.pdf"); doc.Close();
Pass a baseUrl (second parameter) so relative resources (CSS, images, scripts) resolve correctly.
Adding Headers and Footers
SelectPdf lets you define page headers and footers that can include HTML, images, page numbers, dates, or custom text.
HtmlToPdf converter = new HtmlToPdf(); converter.Options.DisplayHeader = true; converter.Options.DisplayFooter = true; // Header customization PdfHtmlSection header = new PdfHtmlSection("<div style='text-align:center;font-weight:bold;'>Report Title</div>", ""); header.Height = 50; converter.Header.Add(header); // Footer customization PdfHtmlSection footer = new PdfHtmlSection("<div style='text-align:center;'>Page: {page_number} / {total_pages}</div>", ""); footer.Height = 40; converter.Footer.Add(footer); PdfDocument doc = converter.ConvertUrl("https://example.com"); doc.Save("with_header_footer.pdf"); doc.Close();
Built-in variables you can use in header/footer HTML:
- {page_number}
- {total_pages}
- {date}
- {time}
- {page_number_x_of_total}
Handling CSS and JavaScript
SelectPdf renders pages including CSS and JavaScript. For complex pages:
- Ensure external CSS and JS are reachable (use absolute URLs or correct baseUrl).
- If JavaScript modifies the DOM after load, use converter.Options.MinPageLoadTime to wait for client-side rendering.
- For single-page apps, you may need to inject a small script that signals readiness or adjust the max load time.
Example:
converter.Options.MinPageLoadTime = 1000; // wait at least 1s converter.Options.MaxPageLoadTime = 10000; // wait up to 10s
Pagination and Page Breaks
To control page breaks in CSS, use:
- page-break-before, page-break-after, page-break-inside
- break-before, break-after, break-inside for modern CSS
Example:
<div style="page-break-after: always;">Section 1</div> <div>Section 2</div>
SelectPdf respects these rules when generating the PDF.
Table of Contents and Bookmarks
SelectPdf allows creating bookmarks and table of contents entries programmatically or by using named anchors in HTML plus custom processing. You can also add PDF bookmarks that mirror document structure.
Simple bookmark creation:
PdfDocument doc = converter.ConvertUrl("https://example.com"); PdfPage firstPage = doc.Pages[0]; PdfOutline root = doc.Outlines.Add("Root Bookmark", firstPage); root.Add("Section 1", firstPage); doc.Save("bookmarked.pdf"); doc.Close();
PDF Security and Permissions
You can secure PDFs with passwords and restrict printing/copying:
PdfDocument doc = converter.ConvertUrl("https://example.com"); doc.Security.OwnerPassword = "ownerpass"; doc.Security.UserPassword = "userpass"; doc.Security.Permissions.Print = false; doc.Security.Permissions.Copy = false; doc.Save("secure.pdf"); doc.Close();
Watermarks, Headers, Stamps
Add text or image watermarks and stamps:
PdfDocument doc = converter.ConvertUrl("https://example.com"); // Text watermark PdfTextSection watermark = new PdfTextSection(0, 0, "CONFIDENTIAL", new System.Drawing.Font("Arial", 40, System.Drawing.FontStyle.Bold)); watermark.ForeColor = System.Drawing.Color.Red; watermark.Opacity = 0.15f; doc.AddWatermark(watermark); // Image watermark (example) PdfImage image = doc.AddImage("logo.png"); image.Opacity = 0.2f; image.SetPosition(200, 400); doc.Save("watermarked.pdf"); doc.Close();
Performance Considerations
- Reuse HtmlToPdf converter instance for multiple conversions when possible to reduce startup overhead.
- For bulk conversions, throttle parallel conversions to avoid excessive CPU/memory usage.
- Cache static resources (CSS, images) on your server to reduce remote fetch latency.
- Use appropriate page size and image compression settings to control output PDF size.
Troubleshooting Common Issues
- Broken CSS/images: ensure baseUrl is correct or use absolute URLs.
- JavaScript-rendered content missing: increase MinPageLoadTime or use a readiness signal.
- Fonts not embedding: ensure fonts are accessible or installed on the server; consider using web fonts.
- Large PDF file sizes: compress images before conversion or use lower-quality images/CSS print rules.
Sample ASP.NET Core Usage (Controller returning PDF)
[HttpGet("export")] public IActionResult Export() { HtmlToPdf converter = new HtmlToPdf(); converter.Options.PdfPageSize = PdfPageSize.A4; string html = "<html><body><h1>Invoice</h1><p>Generated PDF</p></body></html>"; PdfDocument doc = converter.ConvertHtmlString(html); byte[] pdf = doc.Save(); doc.Close(); return File(pdf, "application/pdf", "invoice.pdf"); }
Licensing and Production Notes
- The community/trial editions often add a watermark or have limits—verify before deploying.
- Purchase the appropriate SelectPdf license for your deployment scenario (server, developer, enterprise).
- Store the license key securely and apply it according to SelectPdf documentation.
Alternatives and When to Use SelectPdf
SelectPdf is a strong choice when you need high-fidelity HTML rendering, extensive PDF manipulation features, and .NET-native API. Alternatives include wkhtmltopdf (with wrappers), Puppeteer/Playwright-based converters, IronPDF, and commercial services. Evaluate based on rendering accuracy, performance, licensing cost, and deployment constraints.
Best Practices Summary
- Use absolute URLs or correct baseUrl for resources.
- Tune load-timeouts for JS-heavy pages.
- Add headers/footers and page numbering through SelectPdf API for consistent output.
- Secure PDFs with passwords/permissions if needed.
- Monitor memory/CPU for batch conversions; throttle concurrency.
- Test with production-like HTML/CSS early to catch rendering differences.
If you want, I can:
- Provide a ready-to-drop-in ASP.NET Core middleware example.
- Create example code for converting a JavaScript-heavy single-page app (SPA).
- Compare SelectPdf options vs Puppeteer/Playwright for your specific project.
Leave a Reply