c-sharp
  1. c-sharp-html-to-pdf-c

C# HTML to PDF

In C#, we can convert an HTML file to a PDF file using third-party libraries. In this tutorial, we'll discuss how to use the iTextSharp library to convert an HTML file to a PDF file.

Syntax

The syntax for converting an HTML file to a PDF file using iTextSharp in C# is as follows:

using iTextSharp.text;
using iTextSharp.text.pdf;
using iTextSharp.tool.xml;

public void ConvertHtmlToPdf(string htmlFilePath, string pdfFilePath) {
   Document document = new Document();
   PdfWriter writer = PdfWriter.GetInstance(document, new FileStream(pdfFilePath, FileMode.Create));
   document.Open();
   XMLWorkerHelper.GetInstance().ParseXHtml(writer, document, new FileStream(htmlFilePath, FileMode.Open));
   document.Close();
}

The code above uses the iTextSharp library to create a new PDF document and write the contents of an HTML file to it.

Example

Let's say we have an HTML file called "example.html" and we want to convert it to a PDF file called "example.pdf". Here's how we can implement it:

ConvertHtmlToPdf("example.html", "example.pdf");

Output

When we run the example code above, a new PDF file called "example.pdf" will be created in the same directory as the HTML file.

Explanation

In the example above, we defined a method called "ConvertHtmlToPdf" that takes two parameters: the path to the HTML file and the path to the PDF file. We then used the iTextSharp library to create a new PDF document and write the contents of the HTML file to it.

Use

HTML to PDF conversion can be used in a variety of scenarios where you need to create PDF files from HTML content, such as generating reports or invoices.

Important Points

  • The iTextSharp library can be downloaded and added to your project using the NuGet Package Manager in Visual Studio.
  • The HTML file must be well-formed and follow the XHTML standard in order to be converted to a PDF file.
  • The resulting PDF file may not look identical to the original HTML file, especially for complex layouts and styles.

Summary

In this tutorial, we discussed how to use the iTextSharp library in C# to convert an HTML file to a PDF file. We covered the syntax, example, output, explanation, use, and important points of HTML to PDF conversion using iTextSharp in C#. With this knowledge, you can now use third-party libraries to convert HTML files to PDF files in your C# applications.

Published on: