wkhtmltopdf - convert html code to pdf directly in C#
I just started a new project to provide a C# P/Invoke wrapper around wkhtmltopdf.
You can checkout my code at: https://github.com/pruiz/WkHtmlToXSharp
Greets.
Take a look at Pechkin
.NET Wrapper for WkHtmlToPdf DLL, library that uses Webkit engine to convert HTML pages to PDF.
Nuget packages:
Pechkin.Synchronized
Pechkin
Example code:
private void ConvertToPdf()
{
var loadPath = Server.MapPath("~/HtmlTemplates");
var loadFile = Path.Combine(loadPath, "Test.html");
var savePath = Server.MapPath("~/Pdf");
var saveFile = Path.Combine(savePath, DateTime.Now.ToString("HH-mm-ss.fff") + ".pdf");
var globalConfig = new GlobalConfig()
.SetMargins(0, 0, 0, 0)
.SetPaperSize(PaperKind.A4);
var pdfWriter = new SynchronizedPechkin(globalConfig);
pdfWriter.Error += OnError;
pdfWriter.Warning += OnWarning;
var objectConfig = new ObjectConfig()
.SetPrintBackground(true)
.SetIntelligentShrinking(false);
var pdfBuffer = pdfWriter.Convert(objectConfig, File.ReadAllText(loadFile));
File.WriteAllBytes(saveFile, pdfBuffer);
}
private void OnWarning(SimplePechkin converter, string warningtext)
{
throw new NotImplementedException();
}
private void OnError(SimplePechkin converter, string errortext)
{
throw new NotImplementedException();
}
wkhtmltopdf is a free tool, but it's not written in .NET and it could be kind of hard to integrate into your asp.net application.
you can take a look at iTextSharp, which is free, but cannot handle any kind of html, or you can take a look at commercial tools to convert html to pdf, like ExpertPDF or ABCpdf, that can handle any html/css.