wkhtmltopdf - convert html code to pdf directly in C#
Asked Answered
H

5

9

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!

Himeji answered 18/10, 2010 at 7:34 Comment(1)
Take a look at this question.Magill
L
5

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.

Lorrimor answered 18/10, 2010 at 12:44 Comment(3)
it's not a problem to integrate it in an asp.net applicationGlossographer
iTextSharp has an AGPL copyleft license and cannot be used in commercial applications without making the full source code of the project opened or paying for itExcursive
In my opinion if you want to use WkHtmlToPdf into your C# app. Since the library is built in C++ (github.com/wkhtmltopdf/wkhtmltopdf) and producing a native DLL, I can think about two possible ways for using it from .NET 1. A wrapper library using P/Invoke (DLLimport, ...) for calling native functionality from C#. 2. A wrapper library invoking an executable Each one has its advantages and disadvantages, I haven seen nuget packages for bothUnconditional
L
15

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.

Lipoprotein answered 29/1, 2011 at 19:17 Comment(2)
finally someone who works on .NET wrapper. looks promising. I will check it outInstable
under which license is this distributed ? can it be used for commercial applications ?Kristin
B
9

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();
}
Bubo answered 16/4, 2013 at 9:53 Comment(7)
I just couldn't use this library. Do you have any advice on how exactly I should use it? Trying to install it via nuGet gives me a version error (Install-Package : Could not install package 'Pechkin.Synchronized 0.5.8.1'. You are trying to install this package into a project that targets '.NETFramework,Version=v3.5', but the package does not contain any assembly references or content files that are compatible with that framework.)Calathus
Problem is: I can't even run the dlls inside my web project. Nowhere in the docs I can find what .NET version I should be using. It states not to be compatible with my version, but what version is it compatible with? My PDF generation is working beautifully, full of graphics and coloured tables, but I'm not able to generate it from ASP.NET and this is very frustrating. I feel I'm close but just can't do it.Calathus
@marquito: yeah, it requires .NET 4.0, I checked the dll with JustDecompile and it depends on mscorlib from 4.0Excursive
Hummm... that's bad. Our system is huge and running under 3.5. Thanks for your effort, Mr. @PandaCalathus
@marquito: you might want to just add code.google.com/p/wkhtmltopdf/downloads/list to your server and call it from C#, it has binaries for windows/linuxExcursive
That's what I've been trying to do, to no avail. I feel like a noob. I've tried this: #1332426 It's probably a path issue.Calathus
If you can, please join me at: chat.stackoverflow.com/rooms/37112/wkhtmltopdfCalathus
L
5

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.

Lorrimor answered 18/10, 2010 at 12:44 Comment(3)
it's not a problem to integrate it in an asp.net applicationGlossographer
iTextSharp has an AGPL copyleft license and cannot be used in commercial applications without making the full source code of the project opened or paying for itExcursive
In my opinion if you want to use WkHtmlToPdf into your C# app. Since the library is built in C++ (github.com/wkhtmltopdf/wkhtmltopdf) and producing a native DLL, I can think about two possible ways for using it from .NET 1. A wrapper library using P/Invoke (DLLimport, ...) for calling native functionality from C#. 2. A wrapper library invoking an executable Each one has its advantages and disadvantages, I haven seen nuget packages for bothUnconditional
H
2

I found a way. You can set up another to output the normal html. And use that url as the input value of wkhtml2pdf process.

----------Edit

public byte[] WKHtmlToPdf(string url_input)
    {
        try
        {
            var fileName = " - ";
            var wkhtmlDir = ConfigurationSettings.AppSettings["wkhtmlDir"];
            var wkhtml = ConfigurationSettings.AppSettings["wkhtml"];
            var p = new Process();

            string url = Request.Url.GetLeftPart(UriPartial.Authority) + @"/application/" + url_input;

            p.StartInfo.CreateNoWindow = true;
            p.StartInfo.RedirectStandardOutput = true;
            p.StartInfo.RedirectStandardError = true;
            p.StartInfo.RedirectStandardInput = true;
            p.StartInfo.UseShellExecute = false;
            p.StartInfo.FileName = wkhtml;
            p.StartInfo.WorkingDirectory = wkhtmlDir;

            string switches = "";
            switches += "--print-media-type ";
            switches += "--margin-top 10mm --margin-bottom 10mm --margin-right 10mm --margin-left 10mm ";
            switches += "--page-size Letter ";
            p.StartInfo.Arguments = switches + " " + url + " " + fileName;
            p.Start();

            //read output
            byte[] buffer = new byte[32768];
            byte[] file;
            using (var ms = new MemoryStream())
            {
                while (true)
                {
                    int read = p.StandardOutput.BaseStream.Read(buffer, 0, buffer.Length);

                    if (read <= 0)
                    {
                        break;
                    }
                    ms.Write(buffer, 0, read);
                }
                file = ms.ToArray();
            }

            // wait or exit
            p.WaitForExit(60000);

            // read the exit code, close process
            int returnCode = p.ExitCode;
            p.Close();

            return returnCode == 0 ? file : null;
        }
        catch (Exception ex)
        {

           // set your exceptions here
            return null;
        }
    }

----------web.config key example

  <add key="wkhtmlDir" value="C:\Program Files (x86)\wkhtmltopdf\bin"/>
    <add key="wkhtml" value="C:\Program Files (x86)\wkhtmltopdf\bin\wkhtmltopdf.exe"/>

The basic idea is passing url to the exe as an argument.

HTH !

Himeji answered 20/10, 2010 at 6:15 Comment(0)
C
0

if you want to print specific part of html with Css

install Nuget packages:

Pechkin.Synchronized

StringWriter sw = new StringWriter();
    HtmlTextWriter hw = new HtmlTextWriter(sw);
  pnlprint.RenderControl(hw);
    StringReader sr = new StringReader(sw.ToString());
   string cssPath = Server.MapPath("~/css/style1.css");

    string cssString = File.ReadAllText(cssPath);
     cssPath = Server.MapPath("~/css/bootstrap.css");
    string cssString2 = File.ReadAllText(cssPath);
    cssString += cssString2;
    GlobalConfig gc = new GlobalConfig();
    byte[] pdfContent = new SimplePechkin(new GlobalConfig()).Convert(@"<html><head><style>" + cssString + "</style></head><body>" + sw.ToString() + "</body></html>");

here you can easily understand the working of wkhtmltopdf https://ourcodeworld.com/articles/read/366/how-to-generate-a-pdf-from-html-using-wkhtmltopdf-with-c-in-winforms

Conakry answered 29/4, 2019 at 5:51 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.