Convert HTML String to PDF using Free API in C#

Converting from HTML to PDF is not an easy task. There are some tools that can do this, but most of them costs thousands of dollars. This article provides a free solution with only few lines of C# code, using free Spire.PDF.

Free Spire.PDF is a community edition of the fully featured Spire.PDF for .NET. It allows you to create PDF documents directly from HTML pages in your ASP.NET and MVC Websites, Desktop Applications and Services.

You can use the free library in .NET 4.0 and later applications, in C# and VB.NET languages, on 32-bit and 64-bit Windows machines.

2017-02-07_144504

Using the code

PdfDocument pdf = new PdfDocument();
PdfPageSettings setting = new PdfPageSettings();
setting.Size = PdfPageSize.A4;

PdfHtmlLayoutFormat htmlLayoutFormat = new PdfHtmlLayoutFormat();
htmlLayoutFormat.IsWaiting = false;                    
string htmlCode = File.ReadAllText("HTML example.html");
Thread thread = new Thread(() =>
{ pdf.LoadFromHTML(htmlCode, false, setting, htmlLayoutFormat); });
thread.SetApartmentState(ApartmentState.STA);
thread.Start();
thread.Join();

pdf.SaveToFile("Html2Pdf.pdf");

Output

2017-02-07_144945

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s