Html to pdf with itextsharp

Converting ASP.NET Repeater HTML to PDF using iTextSharp

This article describes you how to convert asp.net repeater controls HTML or entire webpage to pdf using iTextSharp. It will also give introduction to iTextSharp library.

Introduction to iTextSharp

iTextSharp is a free library to create PDF documents using C#.net. It gives you more flexibility to documents in terms of look and feel and overall customization of PDF documents. iTextSharp’s objects like Table, Cell, paragraph, phrase, etc. makes things easy to create professional pdf documents. It allows you to control every pixel and line of PDF file. Using iTextSharp you can only create PDF files. Download the latest iTextSharp dll by clicking here.

Step by step implementation of iTextSharp to convert repeater controls HTML to PDF

Create a Webpage with repeater control

Follow the article Repeater control with custom paging to create aspx page with repeater control.

Export Customers

Add a button control to the aspx page created in the previous step. The functionality for this button would be to export details of customers displayed on the current page. The page has the feature of paging so only customers shown for the current page will be export to PDF using iTextSharp dll.

Читайте также:  Полосы прокрутки

iTextSharp.text.html.simpleparser.HTMLWorker has method Parse which parses string to HTML.

Repeater control’s method RenderControl gives us the required HTML for parsing and with the help of Response objects methods and properties you can convert the HTML to PDF.

Add the below code for btnExport click event.

 protected void btnPDF_Click(object sender, EventArgs e) < Response.ContentType = "application/pdf"; Response.AddHeader("content-disposition", "attachment;filename=Customers.pdf"); Response.Cache.SetCacheability(HttpCacheability.NoCache); StringWriter sw = new StringWriter(); HtmlTextWriter hw = new HtmlTextWriter(sw); //this.Page.RenderControl(hw); this.repCustomers.RenderControl(hw); StringReader sr = new StringReader (sw.ToString().Replace("\r", "") .Replace("\n", "").Replace(" ", "")); Document pdfDoc = new Document(iTextSharp.text.PageSize.A4, 10f, 10f, 10f, 0.0f); HTMLWorker htmlparser = new HTMLWorker(pdfDoc); PdfWriter.GetInstance(pdfDoc, Response.OutputStream); pdfDoc.Open(); htmlparser.Parse(sr); pdfDoc.Close(); Response.Write(pdfDoc); Response.End(); > 

convert Customer HTML page to PDF

Export All Customers

Add a button to the aspx page for converting all customers’ HTML to PDF.

Due to paging, at any given time you will have only customers that are displayed for current page index. So you will have to create a new Repeater control and bind it to all customers using C# code.

Replace below code with this.repCustomers.RenderControl(hw); from the previous step and add it for btnExportAllCustomer_Click event;

It uses the RenderControl method of new repeater control.

 Repeater repAllCustomers = this.repCustomers; repAllCustomers.DataSource = CustomerService.GetAllCustomers (0, CustomerService.GetCustomerCount()); repAllCustomers.DataBind(); repAllCustomers.RenderControl(hw); 

It converts the structure of existing repeater repCustomers control and binds to all customers which are in the Northwind database.

Convert all Customers HTML to PDF

Convert entire Webpage HTML to PDF

If you want to convert the Webpage’s entire HTML to PDF using iTextSharp. Use this.Page.RenderControl(hw); instead of using repAllCustomers.RenderControl.

Whenever you convert HTML to PDF make sure all the links to images, other webpages are accessible or relative addresses used to link.

12/13/2013 12:07 AM ali i’ve a problem whn i convert html to pdf with itexSharp in C# i,ve not the real image of html for example the table isn’t matching give me an ideam inf2050@yahoo.fr thanks

12/15/2013 07:13 AM Laxmikant As we are using ASP.NET Response object to convert html to PDF so it depends on various factor which Response object will use while converting html to PDF. If you want to have absolute control o PDF formatting and data you will have to use iTextSharps object. Go through for more info . http://www.c-sharpcorner.com/UploadFile/f2e803/basic-pdf-creation-using-itextsharp-part-i/

12/29/2013 05:24 AM CooperCloud Is there any way to change the font type using this method?

12/29/2013 07:13 AM Laxmikant @CooperCloud, you have to set it your font to page and its control before you call RenderControl() method of GridView. If you want to have more control on formatting, display, font, color use iTextSharp libary and its table objects

Источник

Convert HTML to PDF in C# with iTextSharp: Step-by-Step Guide

Learn how to easily convert HTML to PDF in C# using iTextSharp library. Follow the step-by-step guidance and code examples provided in this post. Start converting your HTML files today!

  • Installing iTextSharp and iTextSharp.pdfhtml with NuGet
  • Converting HTML Strings to PDF using iTextSharp
  • Converting html to pdf using itextsharp in ASP.NET with C#.NET
  • Converting HTML to PDF in ASP.Net MVC Razor
  • Exporting HTML Strings to PDF in ASP.Net using iTextSharp
  • Converting HTML to PDF in .NET Core using iTextSharp
  • Other helpful code examples for converting HTML to PDF to consider
  • Conclusion
  • How to create PDF from HTML in C# using Itextsharp?
  • How to convert HTML file to PDF in C#?
  • How to convert HTML to PDF and send email in C#?
  • How to convert HTML to PDF in MVC C#?

If you are looking for a way to convert html to pdf in C#, iTextSharp is a third-party library that can help you achieve this goal. It is easy to install and use with NuGet, and it provides a variety of font options, the ability to handle large documents, and can add images and tables to PDF documents.

In this step-by-step guide, we will provide you with all the details you need to know to convert html to pdf using itextsharp in c #. We will go through the installation process of iTextSharp and iTextSharp.pdfhtml with NuGet, and provide code examples for converting HTML strings to PDF using iTextSharp. Additionally, we will show you how to convert HTML to PDF in ASP.Net MVC Razor, export HTML strings to PDF in ASP.Net using iTextSharp, and convert HTML to PDF in .NET Core using iTextSharp.

Installing iTextSharp and iTextSharp.pdfhtml with NuGet

Before we start converting HTML to PDF, we need to install iTextSharp and iTextSharp.pdfhtml with NuGet. iTextSharp.pdfhtml is required to convert HTML to PDF. Here are the steps to do this:

  1. Open your project in Visual Studio.
  2. Right-click on your project in the Solution Explorer, and select “Manage NuGet Packages”.
  3. In the “Browse” tab, search for “iTextSharp” and “iTextSharp.pdfhtml”.
  4. Install both packages.

Once you have installed these packages, you are ready to start converting HTML to PDF using iTextSharp.

Converting HTML Strings to PDF using iTextSharp

iTextSharp provides the HTMLWorker class to parse HTML strings. PdfSaveOptions can be used to create a new PDF file from HTML. Here is the code example for converting HTML strings to PDF using iTextSharp:

using iTextSharp.text; using iTextSharp.text.html.simpleparser; using iTextSharp.text.pdf; using System.IO;public static void ConvertHtmlStringToPdf(string htmlString, string pdfFilePath) < using (FileStream stream = new FileStream(pdfFilePath, FileMode.Create)) < Document pdfDoc = new Document(); PdfWriter writer = PdfWriter.GetInstance(pdfDoc, stream); pdfDoc.Open(); HTMLWorker htmlWorker = new HTMLWorker(pdfDoc); htmlWorker.Parse(new StringReader(htmlString)); pdfDoc.Close(); writer.Close(); >> 

This code creates a new PDF file from an HTML string and saves it to a specified file path.

Converting html to pdf using itextsharp in ASP.NET with C#.NET

http://aspnettutorialonline.blogspot.com/2012/04/converting-html-to-pdf-using-itextsharp Duration: 8:58

Converting HTML to PDF in ASP.Net MVC Razor

iTextSharp can also be used in ASP.Net MVC Razor to convert HTML to PDF. Syncfusion.HtmlToPdfConverter.AspNetCore.Mvc5 is a NuGet package that can be used to convert HTML to PDF in an ASP.NET MVC project. Here is the code example for converting HTML to PDF in ASP.Net MVC Razor:

using Syncfusion.Pdf; using Syncfusion.Pdf.Graphics; using Syncfusion.HtmlConverter;public static void ConvertHtmlToPdf(string htmlString, string pdfFilePath)

This code creates a new PDF file from an HTML string in an ASP.NET MVC project and saves it to a specified file path.

Exporting HTML Strings to PDF in ASP.Net using iTextSharp

If you are not using ASP.Net MVC Razor, iTextSharp can still be used to export HTML strings to PDF in ASP.Net. Here is the code example for exporting HTML strings to PDF in ASP.Net using iTextSharp:

using iTextSharp.text; using iTextSharp.text.pdf; using iTextSharp.tool.xml; using System.IO;public static void ExportHtmlStringToPdf(string htmlString, string pdfFilePath) < using (var memoryStream = new MemoryStream()) < var document = new Document(PageSize.A4, 50, 50, 25, 25); var writer = PdfWriter.GetInstance(document, memoryStream); document.Open(); var htmlWorker = new XMLWorkerHelper(); using (var stringReader = new StringReader(htmlString)) < htmlWorker.ParseXHtml(writer, document, stringReader); document.Close(); writer.Close(); >var bytes = memoryStream.ToArray(); File.WriteAllBytes(pdfFilePath, bytes); > > 

This code creates a new PDF file from an HTML string in an ASP.Net project and saves it to a specified file path.

Converting HTML to PDF in .NET Core using iTextSharp

If you are using .NET Core, iTextSharp is an alternative to iText for HTML to PDF conversion. XML Worker is required for converting HTML to PDF using iTextSharp. Here is the code example for converting HTML to PDF in .NET Core using iTextSharp:

using iTextSharp.text; using iTextSharp.text.pdf; using iTextSharp.tool.xml; using System.IO;public static void ConvertHtmlToPdf(string htmlString, string pdfFilePath) < using (var memoryStream = new MemoryStream()) < var document = new Document(PageSize.A4, 50, 50, 25, 25); var writer = PdfWriter.GetInstance(document, memoryStream); document.Open(); var htmlWorker = new XMLWorker(document); using (var stringReader = new StringReader(htmlString)) < htmlWorker.ParseXHtml(writer, document, stringReader); document.Close(); writer.Close(); >var bytes = memoryStream.ToArray(); File.WriteAllBytes(pdfFilePath, bytes); > > 

This code creates a new PDF file from an HTML string in a .NET Core project and saves it to a specified file path.

Other helpful code examples for converting HTML to PDF to consider

In Html , for instance, itextsharp html to pdf code example

//Create a byte array that will eventually hold our final PDF Byte[] bytes;//Boilerplate iTextSharp setup here //Create a stream that we can write to, in this case a MemoryStream using (var ms = new MemoryStream()) < //Create an iTextSharp Document which is an abstraction of a PDF but **NOT** a PDF using (var doc = new Document()) < //Create a writer that's bound to our PDF abstraction and our stream using (var writer = PdfWriter.GetInstance(doc, ms)) < //Open the document for writing doc.Open(); //Our sample HTML and CSS var example_html = @"

This is some sample text.

"; var example_css = @".headline"; /************************************************** * Example #1 * * * * Use the built-in HTMLWorker to parse the HTML. * * Only inline CSS is supported. * * ************************************************/ //Create a new HTMLWorker bound to our document using (var htmlWorker = new iTextSharp.text.html.simpleparser.HTMLWorker(doc)) < //HTMLWorker doesn't read a string directly but instead needs a TextReader (which StringReader subclasses) using (var sr = new StringReader(example_html)) < //Parse the HTML htmlWorker.Parse(sr); >> /************************************************** * Example #2 * * * * Use the XMLWorker to parse the HTML. * * Only inline CSS and absolutely linked * * CSS is supported * * ************************************************/ //XMLWorker also reads from a TextReader and not directly from a string using (var srHtml = new StringReader(example_html)) < //Parse the HTML iTextSharp.tool.xml.XMLWorkerHelper.GetInstance().ParseXHtml(writer, doc, srHtml); >/************************************************** * Example #3 * * * * Use the XMLWorker to parse HTML and CSS * * ************************************************/ //In order to read CSS as a string we need to switch to a different constructor //that takes Streams instead of TextReaders. //Below we convert the strings into UTF8 byte array and wrap those in MemoryStreams using (var msCss = new MemoryStream(System.Text.Encoding.UTF8.GetBytes(example_css))) < using (var msHtml = new MemoryStream(System.Text.Encoding.UTF8.GetBytes(example_html))) < //Parse the HTML iTextSharp.tool.xml.XMLWorkerHelper.GetInstance().ParseXHtml(writer, doc, msHtml, msCss); >> doc.Close(); > > //After all of the PDF "stuff" above is done and closed but **before** we //close the MemoryStream, grab all of the active bytes from the stream bytes = ms.ToArray(); >//Now we just need to do something with those bytes. //Here I'm writing them to disk but if you were in ASP.Net you might Response.BinaryWrite() them. //You could also write the bytes to a database in a varbinary() column (but please don't) or you //could pass them to another function for further PDF processing. var testFile = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "test.pdf"); System.IO.File.WriteAllBytes(testFile, bytes);

Conclusion

iTextSharp is a powerful tool for converting HTML to PDF in C#. It provides a variety of font options, the ability to handle large documents, and can add images and tables to PDF documents. IronPDF and Api2Pdf are pragmatic alternatives to iTextSharp that can also be used for HTML to PDF conversion in C#. ChromePdfRenderer can be used with iTextSharp to convert HTML to PDF without losing formatting. With the code examples provided in this article, you can start converting HTML to PDF using iTextSharp in C# with ease.

Источник

Оцените статью