How to generate PDF File from HTML using iTextSharp – C#

Posted by

To generate a PDF file from HTML using iTextSharp in C#, you can follow these steps:

  1. Make sure you have the iTextSharp library installed in your project. You can download it from the official website or use a package manager like NuGet to install it.
  2. Import the necessary namespaces in your code file:
using System.IO;
using iTextSharp.text;
using iTextSharp.text.pdf;
using iTextSharp.tool.xml;
  1. Write code to create and populate the PDF document from an HTML string. Here’s an example that converts an HTML string to a PDF file:
// Create a new document
Document document = new Document();

// Set up the PDF writer and create the file stream
PdfWriter writer = PdfWriter.GetInstance(document, new FileStream("output.pdf", FileMode.Create));

// Open the document for writing

// Read the HTML content from a string
string htmlContent = "<html><body><h1>Hello, World!</h1></body></html>";

// Create a new StringReader to parse the HTML
StringReader sr = new StringReader(htmlContent);

// Parse the HTML and add it to the PDF document
XMLWorkerHelper.GetInstance().ParseXHtml(writer, document, sr);

// Close the document
  1. Build and run your application. After execution, a PDF file named “output.pdf” will be generated in the specified location, containing the content from the HTML string.

Note that iTextSharp uses the XMLWorkerHelper class to parse and convert HTML content to PDF. This class handles HTML tags, styles, and formatting during the conversion process.

Make sure to handle any necessary exceptions that may occur during the PDF generation process and properly dispose of resources when you’re finished using the library.

Additionally, you can customize the PDF generation by adjusting the CSS styles, adding additional HTML content, or using iTextSharp’s rich set of features for PDF manipulation.

Please note that iTextSharp is no longer maintained. You may consider using the iText 7 library, which is the latest version and actively maintained by the iText company. The code structure will be slightly different in iText 7, but the general approach remains the same.