Skip to main content

HTML to PDF Csharp comparison

HTML to PDFPhoto from Unsplash

Originally Posted On: https://ironpdf.com/blog/compare-to-other-components/html-to-pdf-csharp-comparison/

 

 

HTML to PDF in C# for .NET Developers (The Ultimate Guide)

Introduction

In today’s web-driven world, the ability to convert HTML content into PDF documents is a crucial feature for many applications. Whether it’s for generating reports, invoices, or saving web pages for offline use, HTML to PDF conversion plays a pivotal role in streamlining workflows and enhancing user experiences. For .NET developers, choosing the right tool to handle this conversion can significantly impact the efficiency and quality of their applications.

In this article, we’ll explore how to convert HTML to PDF in C# by covering the following topics:

  1. Why Compare HTML to PDF Tools? 2. IronPDF: HTML to PDF Conversion
  2. Aspose: HTML to PDF Conversion 4. iText7: HTML to PDF Conversion
  3. wkhtmltopdf: HTML to PDF Conversion 6. PuppeteerSharp: HTML to PDF Conversion
  4. Conclusion Why Choose IronPDF?

By the end, you’ll understand why IronPDF stands out as a developer-friendly and efficient HTML to PDF converter.

Why Compare HTML to PDF Tools?

Selecting the appropriate HTML to PDF conversion tool is essential for ensuring that your application meets performance, quality, and cost requirements. With numerous options available, each offering different features and capabilities, a thorough comparison helps in making an informed decision. Here are the key evaluation criteria to consider:

  • Integration Complexity: How easily the library integrates with your existing .NET projects.
  • Code Simplicity: The ease of writing and maintaining code using the library.
  • Rendering Accuracy: The ability to accurately render complex HTML, CSS, and JavaScript.
  • Performance at Scale: How well the library performs under heavy load and large-scale PDF generation.
  • Licensing and Cost-Effectiveness: The pricing models and licensing terms suitable for your project’s budget.

By assessing these factors, you can choose a tool that not only fits your technical requirements but also aligns with your project’s financial constraints.

IronPDF: HTML to PDF Conversion

HTML to PDF in C# for .NET Developers (The Ultimate Guide): Figure 1

IronPDF is a full-featured .NET library for converting HTML to PDF. It supports HTML strings, local HTML files, and URLs, making it versatile for a wide range of use cases. Here’s how IronPDF handles each scenario:

HTML String to PDF

Converting HTML from a string to a PDF is simple with IronPDF. This approach is ideal for dynamic content generation or small HTML snippets.

Example:

  1. using IronPdf;
  2. class Program
  3. {
  4. static void Main(string[] args)
  5. {
  6. var renderer = new ChromePdfRenderer();
  7. PdfDocument pdf = renderer.RenderHtmlAsPdf("<h1>Hello, World!</h1>");
  8. PDF.SaveAs("output.pdf");
  9. }
  10. }

HTML to PDF in C# for .NET Developers (The Ultimate Guide): Figure 2

Explanation:

  1. ChromePdfRenderer: The ChromePdfRenderer class is the primary tool for converting HTML to PDF in IronPDF. It comes pre-configured to handle most use cases with minimal setup.
  2. RenderHtmlAsPdf: This method takes an HTML string as input and generates a PDF document.
  3. SaveAs: The generated PDF is saved to the specified path (output.pdf).

Local HTML File to PDF

For applications that need to convert a local HTML file (with external resources like CSS or JavaScript), IronPDF makes it easy.

Example:

  1. using IronPdf;
  2. class Program
  3. {
  4. static void Main(string[] args)
  5. {
  6. var renderer = new ChromePdfRenderer();
  7. PdfDocument pdf = renderer.RenderHtmlFileAsPdf("template.html");
  8. pdf.SaveAs("report.pdf");
  9. }
  10. }

Input HTML File

HTML to PDF in C# for .NET Developers (The Ultimate Guide): Figure 3

Output

HTML to PDF in C# for .NET Developers (The Ultimate Guide): Figure 4

Explanation:

  • RenderHtmlFileAsPdf: Takes a local HTML file and converts it into a PDF.
  • Handles linked resources automatically, such as external CSS and JavaScript files.

URL to PDF

IronPDF is especially powerful when converting dynamic web content from URLs, including pages that use JavaScript.

Example:

  1. using IronPdf;
  2. class Program
  3. {
  4. static void Main(string[] args)
  5. {
  6. var renderer = new ChromePdfRenderer();
  7. PdfDocument pdf = renderer.RenderUrlAsPdf("https://ironpdf.com");
  8. pdf.SaveAs("url-to-pdf.pdf");
  9. }
  10. }

HTML to PDF in C# for .NET Developers (The Ultimate Guide): Figure 5

Explanation:

  • RenderUrlAsPdf: Fetches the URL content, including JavaScript-rendered elements, and converts it to PDF.

Aspose: HTML to PDF Conversion

HTML to PDF in C# for .NET Developers (The Ultimate Guide): Figure 6

Aspose.PDF is another powerful library for PDF manipulation, with support for converting HTML to PDF. Let’s see how Aspose handles each conversion scenario:

HTML String to PDF

Aspose requires a bit more setup when converting HTML strings compared to IronPDF.

Example:

  1. using Aspose.Html;
  2. Document doc = new Document();
  3. Page page = doc.getPages().add();
  4. HtmlFragment htmlFragment = new HtmlFragment("<h1>HTML String</h1>");
  5. page.getParagraphs().add(htmlFragment);
  6. doc.save(dataDir + "HTMLStringUsingDOM.pdf");

Explanation:

  • Document doc: Creates a new document to save the converted HTML string to.
  • Page page: This line adds a new page to the empty document we created.
  • HtmlFragment htmlFragment: This is the HTML string we are converting.
  • page.getParagraphs().add(htmlFragment): Add the HTML to the document
  • doc.save: Saves the document with the HTML content as a PDF document.

Local HTML File to PDF

Aspose also handles converting local HTML files to PDFs, but it requires more configuration than IronPDF.

Example:

  1. using Aspose.Html;
  2. using Aspose.Html.Converters;
  3. using Aspose.Html.Saving;
  4. using var document = new HTMLDocument("document.html");
  5. var options = new PdfSaveOptions();
  6. Converter.ConvertHTML(document, options, "output.pdf");

Explanation:

  • using var document = new HTMLDocument(“document.html”): Loads the HTML file.
  • var options: Creates a new PdfSaveOptions object
  • Converter.ConvertHTML(): Converts the HTML to PDF.

URL to PDF

Aspose provides similar functionality for URLs but requires extra setup.

Example:

  1. using System.IO;
  2. using System;
  3. using System.Net;
  4. using Aspose.Pdf;
  5. string dataDir = "YOUR DOCUMENT DIRECTORY"; // Replace with your path
  6. WebRequest request = WebRequest.Create("https://en.wikipedia.org/wiki/Main_Page");
  7. request.Credentials = CredentialCache.DefaultCredentials;
  8. HttpWebResponse response = (HttpWebResponse)request.GetResponse();
  9. Stream dataStream = response.GetResponseStream();
  10. StreamReader reader = new StreamReader(dataStream);
  11. string responseFromServer = reader.ReadToEnd();
  12. reader.Close();
  13. dataStream.Close();
  14. response.Close();
  15. MemoryStream stream = new MemoryStream(System.Text.Encoding.UTF8.GetBytes(responseFromServer));
  16. HtmlLoadOptions options = new HtmlLoadOptions("https://en.wikipedia.org/wiki/");
  17. Document pdfDocument = new Document(stream, options);
  18. pdfDocument.Save(dataDir + "WebPageToPDF_out.pdf");

Explanation:

  • The dataDir variable holds the directory where the generated PDF will be saved.
  • A WebRequest is created to access the Wikipedia main page URL, and default credentials are used for the request.
  • The GetResponse() method sends the request and retrieves the response as an HttpWebResponse.
  • A stream is obtained from the response, and a StreamReader reads the entire HTML content of the page into the responseFromServer string.
  • The HTML content from responseFromServer is converted into a byte array and then loaded into a MemoryStream.
  • HtmlLoadOptions is used to specify the base URL for relative links and other settings.
  • An Aspose.Pdf.Document is created from the memory stream containing the HTML, and the document is saved as a PDF to the specified directory.

iText7: HTML to PDF Conversion

HTML to PDF in C# for .NET Developers (The Ultimate Guide): Figure 7

iText7 is a comprehensive PDF library that also supports HTML-to-PDF conversion. Here’s how iText7 performs in different scenarios:

HTML String to PDF

iText7 makes use of its htmlConverter class to convert HTML string to PDF format.

Example:

  1. public static String DEST = String.Format("{0}test-03.pdf", TARGET);
  2. var html = "<h1>Hello World</h1>";
  3. HtmlConverter.ConvertToPdf(html, new FileStream(dest, FileMode.Create));

Local HTML File to PDF

iText7 can convert HTML file types to PDF using the HtmlConverter.ConvertToPdf class.

Example:

  1. using iText.Html2pdf;
  2. class Program
  3. {
  4. static void Main(string[] args)
  5. {
  6. HtmlConverter.ConvertToPdf("template.html", new FileStream("html-file-to-pdf.pdf", FileMode.Create));
  7. }
  8. }

Explanation:

  • HtmlConverter: Converts an HTML file directly to a PDF.

URL to PDF

iText7 also supports converting content from URLs.

Example:

  1. using iText.Html2pdf;
  2. class Program
  3. {
  4. static void Main(string[] args)
  5. {
  6. HtmlConverter.ConvertToPdf("https://example.com", new FileStream("url-to-pdf.pdf", FileMode.Create));
  7. }
  8. }

Explanation:

  • HtmlConverter: Manages the URL content and converts it into a PDF.

wkhtmltopdf: HTML to PDF Conversion

HTML to PDF in C# for .NET Developers (The Ultimate Guide): Figure 8

wkhtmltopdf is a command-line tool that converts HTML files to PDF using Webkit rendering. Here’s how it works for different scenarios:

HTML String to PDF

wkhtmltopdf requires converting HTML strings by writing them to a file first.

Example:

  1. using System;
  2. using System.IO;
  3. using System.Diagnostics;
  4. class Program
  5. {
  6. static void Main(string[] args)
  7. {
  8. // HTML string to be converted to PDF
  9. string html = "<html><body><h1>Hello, World!</h1></body></html>";
  10. // Write HTML string to temporary file
  11. string tempHtmlFile = Path.Combine(Path.GetTempPath(), "temp.html");
  12. File.WriteAllText(tempHtmlFile, html);
  13. // Set output PDF path
  14. string outputPdfFile = Path.Combine(Path.GetTempPath(), "html-string-to-pdf.pdf");
  15. // Execute wkhtmltopdf command
  16. Process process = new Process();
  17. process.StartInfo.FileName = "wkhtmltopdf";
  18. process.StartInfo.Arguments = $"\"{tempHtmlFile}\" \"{outputPdfFile}\"";
  19. process.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
  20. process.Start();
  21. process.WaitForExit();
  22. // Clean up the temporary HTML file
  23. File.Delete(tempHtmlFile);
  24. Console.WriteLine($"PDF saved to: {outputPdfFile}");
  25. }
  26. }

Explanation:

  • wkhtmltopdf requires an input file, so we first write the HTML string to a temporary file (temp.html).
  • We then use the Process class to execute the wkhtmltopdf command, passing the file path of the temporary HTML file and the desired output PDF path as arguments.
  • After conversion, we delete the temporary HTML file to clean up.

Local HTML File to PDF

For converting a local HTML file to a PDF using wkhtmltopdf, you can directly point to the file path of the HTML file.

Example:

  1. using System;
  2. using System.Diagnostics;
  3. class Program
  4. {
  5. static void Main(string[] args)
  6. {
  7. // Path to the local HTML file
  8. string htmlFilePath = @"C:\path\to\your\template.html";
  9. // Path for the output PDF file
  10. string outputPdfFile = @"C:\path\to\output\html-file-to-pdf.pdf";
  11. // Execute wkhtmltopdf command
  12. Process process = new Process();
  13. process.StartInfo.FileName = "wkhtmltopdf";
  14. process.StartInfo.Arguments = $"\"{htmlFilePath}\" \"{outputPdfFile}\"";
  15. process.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
  16. process.Start();
  17. process.WaitForExit();
  18. Console.WriteLine($"PDF saved to: {outputPdfFile}");
  19. }
  20. }

Explanation:

  • This example simply provides the path to the local HTML file (template.html) and the output path for the PDF.
  • wkhtmltopdf directly handles local files, making the command straightforward.

URL to PDF

Converting a URL to a PDF is easy with wkhtmltopdf. Just pass the URL directly to the command.

Example:

  1. using System;
  2. using System.Diagnostics;
  3. class Program
  4. {
  5. static void Main(string[] args)
  6. {
  7. // URL to be converted to PDF
  8. string url = "https://example.com";
  9. // Path for the output PDF file
  10. string outputPdfFile = @"C:\path\to\output\url-to-pdf.pdf";
  11. // Execute wkhtmltopdf command
  12. Process process = new Process();
  13. process.StartInfo.FileName = "wkhtmltopdf";
  14. process.StartInfo.Arguments = $"\"{url}\" \"{outputPdfFile}\"";
  15. process.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
  16. process.Start();
  17. process.WaitForExit();
  18. Console.WriteLine($"PDF saved to: {outputPdfFile}");
  19. }
  20. }

Explanation:

  • In this example, wkhtmltopdf directly accepts URLs as input.
  • The URL is passed as an argument to wkhtmltopdf, and the output is saved as a PDF to the specified path

PuppeteerSharp: HTML to PDF Conversion

HTML to PDF in C# for .NET Developers (The Ultimate Guide): Figure 9

PuppeteerSharp is a powerful tool for automating headless Chrome or Chromium, often used for web scraping or rendering complex web pages. Below are examples of how to use PuppeteerSharp for converting HTML to PDF.

HTML String to PDF

Puppeteer is designed for rendering full pages, so converting an HTML string requires writing it to a file or rendering it directly in a browser.

Example:

  1. using PuppeteerSharp;
  2. using System;
  3. using System.Threading.Tasks;
  4. class Program
  5. {
  6. static async Task Main(string[] args)
  7. {
  8. // Download the browser if necessary
  9. await new BrowserFetcher().DownloadAsync(BrowserFetcher.DefaultRevision);
  10. var browser = await Puppeteer.LaunchAsync(new LaunchOptions { Headless = true });
  11. var page = await browser.NewPageAsync();
  12. string htmlContent = "<h1>Hello, World!</h1><p>This is a PDF generated from HTML string.</p>";
  13. await page.SetContentAsync(htmlContent);
  14. // Save the page as a PDF
  15. await page.PdfAsync("html-string-to-pdf.pdf");
  16. await browser.CloseAsync();
  17. }
  18. }

Explanation:

  • Puppeteer.LaunchAsync: Launches a new instance of Chromium in headless mode.
  • page.SetContentAsync: Loads the HTML string into the browser page.
  • page.PdfAsync: Converts the loaded HTML into a PDF and saves it to a file.

Local HTML File to PDF

To convert a local HTML file into a PDF using PuppeteerSharp, you can load the file into a headless browser and generate the PDF.

Example:

  1. using PuppeteerSharp;
  2. using System;
  3. using System.Threading.Tasks;
  4. class Program
  5. {
  6. static async Task Main(string[] args)
  7. {
  8. // Download the browser if necessary
  9. await new BrowserFetcher().DownloadAsync(BrowserFetcher.DefaultRevision);
  10. var browser = await Puppeteer.LaunchAsync(new LaunchOptions { Headless = true });
  11. var page = await browser.NewPageAsync();
  12. // Load the local HTML file
  13. await page.GoToAsync("file:///path/to/your/template.html");
  14. // Save the page as a PDF
  15. await page.PdfAsync("html-file-to-pdf.pdf");
  16. await browser.CloseAsync();
  17. }
  18. }

Explanation:

  • page.GoToAsync: Loads the local HTML file (make sure to use the correct [file://]() path).
  • page.PdfAsync: Converts the content of the local HTML file into a PDF.

URL to PDF

Converting a URL to a PDF is one of the core features of PuppeteerSharp, as it can handle complex pages with JavaScript.

Example:

  1. using PuppeteerSharp;
  2. using System;
  3. using System.Threading.Tasks;
  4. class Program
  5. {
  6. static async Task Main(string[] args)
  7. {
  8. // Download the browser if necessary
  9. await new BrowserFetcher().DownloadAsync(BrowserFetcher.DefaultRevision);
  10. var browser = await Puppeteer.LaunchAsync(new LaunchOptions { Headless = true });
  11. var page = await browser.NewPageAsync();
  12. // Navigate to the URL
  13. await page.GoToAsync("https://example.com");
  14. // Save the page as a PDF
  15. await page.PdfAsync("url-to-pdf.pdf");
  16. await browser.CloseAsync();
  17. }
  18. }

Explanation:

  • page.GoToAsync: Navigates to the specified URL.
  • page.PdfAsync: Converts the web page at the URL into a PDF and saves it.

Why Choose IronPDF?

IronPDF stands out due to its ease of use, flexibility, and seamless integration with .NET applications. It is simple to implement, supports HTML, CSS, and JavaScript rendering, and doesn’t require additional setup or external dependencies. Beyond HTML to PDF conversion, IronPDF offers a extensive range of features for creating PDF documents from various file types, editing and adding to existing PDF documents, watermarking, PDF file security, and more! To see more of this library in action, be sure to check out the How-to Guides which demonstrate each of its features at work.

Conclusion

When it comes to converting HTML to PDF files in C#, there are several powerful tools available, each offering unique features and capabilities. IronPDF, Aspose, iText7, wkhtmltopdf, and PuppeteerSharp all provide robust solutions for turning HTML content into professional-grade PDF documents. However, choosing the right tool for your project depends on factors like ease of integration, support for dynamic content, performance, and flexibility.

HTML to PDF in C# for .NET Developers (The Ultimate Guide): Figure 10

  • IronPDF stands out for its simplicity, direct integration with .NET, and ability to handle complex HTML, including JavaScript-rendered pages. It’s perfect for developers looking for an easy-to-use solution with minimal setup.
  • Aspose offers extensive PDF manipulation features, but its HTML-to-PDF conversion capabilities require more configuration, especially for handling local files and external resources.
  • iText7 provides a solid foundation for those looking to create PDF documents, though it may require additional coding to convert HTML to PDF, especially for dynamic content. It’s a great choice for projects where custom PDF manipulation is needed.
  • wkhtmltopdf is ideal for basic HTML-to-PDF conversion with a command-line interface, but it lacks the integration and flexibility of a full .NET library.
  • PuppeteerSharp, leveraging headless Chrome, is the go-to tool for rendering complex, dynamic web pages and converting them into PDFs, especially when dealing with JavaScript-heavy content.

For most .NET developers looking for an all-in-one, straightforward solution, IronPDF today to experience its powerful features for yourself.

Ultimately, the right tool depends on your specific requirements, but with the options discussed here, you’re well-equipped to find the perfect solution for your project.

Stock Quote API & Stock News API supplied by www.cloudquote.io
Quotes delayed at least 20 minutes.
By accessing this page, you agree to the following
Privacy Policy and Terms and Conditions.