Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

wkhtmltopdf - convert html code to pdf directly in C#

I know this tool looks up on a url and converts the repsponse to pdf. How do I convert a

<html> content.. </html> 

into a pdf?

I was looking at the help files on wkhtml2pdf and looks like it provides an option of stdin but I can't really figure out how to emulate stdin.

Also if you know a tool which does a better job, please suggest me some.

Thanks a lot!

like image 550
rlee923 Avatar asked Oct 18 '10 07:10

rlee923


2 Answers

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.

like image 116
Pablo Ruiz García Avatar answered Sep 23 '22 17:09

Pablo Ruiz García


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();
}
like image 30
Răzvan Flavius Panda Avatar answered Sep 22 '22 17:09

Răzvan Flavius Panda