Convert HTML to PDF in .NET

后端 未结 30 1807
不知归路
不知归路 2020-11-22 00:28

I want to generate a PDF by passing HTML contents to a function. I have made use of iTextSharp for this but it does not perform well when it encounters tables and the layout

相关标签:
30条回答
  • 2020-11-22 00:42

    Here is a wrapper for wkhtmltopdf.dll by pruiz

    And a wrapper for wkhtmltopdf.exe by Codaxy
    - also on nuget.

    0 讨论(0)
  • 2020-11-22 00:43

    If you don't really need a true .Net PDF library, there are numerous free HTML to PDF tools, many of which can run from a command-line.

    One solution would be to pick one of those and then write a thin wrapper around that in C#. E.g., as done in this tutorial.

    0 讨论(0)
  • 2020-11-22 00:43

    You need to use a commercial library if you need perfect html rendering in pdf.

    ExpertPdf Html To Pdf Converter is very easy to use and it supports the latest html5/css3. You can either convert an entire url to pdf:

    using ExpertPdf.HtmlToPdf; 
    byte[] pdfBytes = new PdfConverter().GetPdfBytesFromUrl(url);
    

    or a html string:

    using ExpertPdf.HtmlToPdf; 
    byte[] pdfBytes = new PdfConverter().GetPdfBytesFromHtmlString(html, baseUrl);
    

    You also have the alternative to directly save the generated pdf document to a Stream of file on the disk.

    0 讨论(0)
  • 2020-11-22 00:45

    You can use Google Chrome print-to-pdf feature from its headless mode. I found this to be the simplest yet the most robust method.

    var url = "https://stackoverflow.com/questions/564650/convert-html-to-pdf-in-net";
    var chromePath = @"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe";
    var output = Path.Combine(Environment.CurrentDirectory, "printout.pdf");
    using (var p = new Process())
        {
            p.StartInfo.FileName = chromePath;
            p.StartInfo.Arguments = $"--headless --disable-gpu --print-to-pdf={output} {url}";
            p.Start();
            p.WaitForExit();
        }
    
    
    0 讨论(0)
  • 2020-11-22 00:48

    Most HTML to PDF converter relies on IE to do the HTML parsing and rendering. This can break when user updates their IE. Here is one that does not rely on IE.

    The code is something like this:

    EO.Pdf.HtmlToPdf.ConvertHtml(htmlText, pdfFileName);
    

    Like many other converters, you can pass text, file name, or Url. The result can be saved into a file or a stream.

    0 讨论(0)
  • 2020-11-22 00:49

    Best Tool i have found and used for generating PDF of javascript and styles rendered views or html pages is phantomJS.

    Download the .exe file with the rasterize.js function found in root of exe of example folder and put inside solution.

    It Even allows you to download the file in any code without opening that file also it also allows to download the file when the styles and specially jquery are applied.

    Following code generate PDF File :

    public ActionResult DownloadHighChartHtml()
    {
        string serverPath = Server.MapPath("~/phantomjs/");
        string filename = DateTime.Now.ToString("ddMMyyyy_hhmmss") + ".pdf";
        string Url = "http://wwwabc.com";
    
        new Thread(new ParameterizedThreadStart(x =>
        {
            ExecuteCommand(string.Format("cd {0} & E: & phantomjs rasterize.js {1} {2} \"A4\"", serverPath, Url, filename));
                               //E: is the drive for server.mappath
        })).Start();
    
        var filePath = Path.Combine(Server.MapPath("~/phantomjs/"), filename);
    
        var stream = new MemoryStream();
        byte[] bytes = DoWhile(filePath);
    
        Response.ContentType = "application/pdf";
        Response.AddHeader("content-disposition", "attachment;filename=Image.pdf");
        Response.OutputStream.Write(bytes, 0, bytes.Length);
        Response.End();
        return RedirectToAction("HighChart");
    }
    
    
    
    private void ExecuteCommand(string Command)
    {
        try
        {
            ProcessStartInfo ProcessInfo;
            Process Process;
    
            ProcessInfo = new ProcessStartInfo("cmd.exe", "/K " + Command);
    
            ProcessInfo.CreateNoWindow = true;
            ProcessInfo.UseShellExecute = false;
    
            Process = Process.Start(ProcessInfo);
        }
        catch { }
    }
    
    
    private byte[] DoWhile(string filePath)
    {
        byte[] bytes = new byte[0];
        bool fail = true;
    
        while (fail)
        {
            try
            {
                using (FileStream file = new FileStream(filePath, FileMode.Open, FileAccess.Read))
                {
                    bytes = new byte[file.Length];
                    file.Read(bytes, 0, (int)file.Length);
                }
    
                fail = false;
            }
            catch
            {
                Thread.Sleep(1000);
            }
        }
    
        System.IO.File.Delete(filePath);
        return bytes;
    }
    
    0 讨论(0)
提交回复
热议问题