After spending the last few days trying to find code online have just managed to find some code which works at last
By using iTextSharp (V5.0 Ended With V5.5.13.3)
The following code will convert an html string with css parameters to a pdf file saved on the server where you choose the path and filename.
If using css you need to have a ccs file in this example called StyleSheet.css in the root directory, you can then either call a class from an html tag to the main css file, or use inline styles without calling the ccs file, but will have to be like this as an example:-
var html = "<table class='table'>" + // Call to .table style on ccs file //
"<tr ....... >" +
"</table>";
or
var html = "<table style='width: 400px'>" + // In line style no call to css file //
"<tr ....... >" +
"</table>";
You need to at least set up a blank ccs file for it to work even if you are just using in line styles or are not going to even use any css to keep the code happy, also notice I am using single quotes above around table class='table' & table style='width: 400px'
// Using statements C# //
using System;
using System.IO;
using System.Web;
using iTextSharp.text;
using iTextSharp.text.pdf;
using iTextSharp.tool.xml;
// Actual code C# //
var html = // Your html string & including any css parameters //
byte[] pdf;
var cssText = File.ReadAllText(MapPath("~/StyleSheet.css"));
using (var memoryStream = new MemoryStream())
{
var document = new Document(PageSize.A4, 50, 50, 60, 60);
var writer = PdfWriter.GetInstance(document, memoryStream);
document.Open();
using (var cssMemoryStream = new MemoryStream(System.Text.Encoding.UTF8.GetBytes(cssText)))
{
using (var htmlMemoryStream = new MemoryStream(System.Text.Encoding.UTF8.GetBytes(html)))
{
XMLWorkerHelper.GetInstance().ParseXHtml(writer, document, htmlMemoryStream, cssMemoryStream);
}
document.Close();
var Path = "~/Pdf/";
var FileName = "Test.pdf";
System.IO.FileStream file = System.IO.File.Create(HttpContext.Current.Server.MapPath(Path + FileName));
pdf = memoryStream.ToArray();
file.Write(pdf, 0, pdf.Length);
file.Close();
}
}