我想通过将HTML内容传递给函数来生成PDF。我已经为此使用了iTextSharp,但它在遇到表和布局时表现不佳。

有没有更好的办法?


当前回答

最后更新:2020年10月

这是我整理的。net中HTML到PDF转换的选项列表(有些是免费的,有些是付费的)

GemBox.Document https://www.nuget.org/packages/GemBox.Document/ Free (up to 20 paragraphs) $680 - https://www.gemboxsoftware.com/document/pricelist https://www.gemboxsoftware.com/document/examples/c-sharp-convert-html-to-pdf/307 PDF Metamorphosis .Net https://www.nuget.org/packages/sautinsoft.pdfmetamorphosis/ $539 - $1078 - https://www.sautinsoft.com/products/pdf-metamorphosis/order.php https://www.sautinsoft.com/products/pdf-metamorphosis/convert-html-to-pdf-dotnet-csharp.php HtmlRenderer.PdfSharp https://www.nuget.org/packages/HtmlRenderer.PdfSharp/1.5.1-beta1 BSD-UNSPECIFIED License PuppeteerSharp https://www.puppeteersharp.com/examples/index.html MIT License https://github.com/kblok/puppeteer-sharp EO.Pdf https://www.nuget.org/packages/EO.Pdf/ $799 - https://www.essentialobjects.com/Purchase.aspx?f=3 WnvHtmlToPdf_x64 https://www.nuget.org/packages/WnvHtmlToPdf_x64/ $750 - $1600 - http://www.winnovative-software.com/Buy.aspx demo - http://www.winnovative-software.com/demo/default.aspx IronPdf https://www.nuget.org/packages/IronPdf/ $399 - $1599 - https://ironpdf.com/licensing/ https://ironpdf.com/examples/using-html-to-create-a-pdf/ Spire.PDF https://www.nuget.org/packages/Spire.PDF/ Free (up to 10 pages) $599 - $1799 - https://www.e-iceblue.com/Buy/Spire.PDF.html https://www.e-iceblue.com/Tutorials/Spire.PDF/Spire.PDF-Program-Guide/Convert-HTML-to-PDF-Customize-HTML-to-PDF-Conversion-by-Yourself.html Aspose.Html https://www.nuget.org/packages/Aspose.Html/ $599 - $1797 - https://purchase.aspose.com/pricing/html/net https://docs.aspose.com/html/net/html-to-pdf-conversion/ EvoPDF https://www.nuget.org/packages/EvoPDF/ $450 - $1200 - http://www.evopdf.com/buy.aspx ExpertPdfHtmlToPdf https://www.nuget.org/packages/ExpertPdfHtmlToPdf/ $550 - $1200 - https://www.html-to-pdf.net/Pricing.aspx Zetpdf https://zetpdf.com $299 - $599 - https://zetpdf.com/pricing/ Is not a well know or supported library - ZetPDF - Does anyone know the background of this Product? PDFtron https://www.pdftron.com/documentation/samples/cs/HTML2PDFTes $4000/year - https://www.pdftron.com/licensing/ WkHtmlToXSharp https://github.com/pruiz/WkHtmlToXSharp Free Concurrent conversion is implemented as processing queue. SelectPDF https://www.nuget.org/packages/Select.HtmlToPdf/ Free (up to 5 pages) $499 - $799 - https://selectpdf.com/pricing/ https://selectpdf.com/pdf-library-for-net/

如果上面的选项都帮不了你,你可以搜索NuGet包: https://www.nuget.org/packages?q=html+pdf

其他回答

与Winnovative HTML到PDF转换器,您可以转换HTML字符串在单行

byte[] outPdfBuffer = htmlToPdfConverter.ConvertHtml(htmlString, baseUrl);

基URL用于解析HTML字符串中相对URL引用的图像。另外,你也可以在HTML中使用完整的url,或者使用src="data:image/png"作为图像标签嵌入图像。

在回答'fubaar'用户对Winnovative转换器的评论时,有必要进行更正。转换器不使用IE作为渲染引擎。它实际上不依赖于任何安装的软件,并且渲染与WebKit引擎兼容。

尝试这个PDF Duo . net转换组件将HTML从ASP转换为PDF。NET应用程序,而不使用额外的dll。

您可以传递HTML字符串或文件或流来生成PDF。 使用下面的代码(示例c#):

string file_html = @"K:\hdoc.html";   
string file_pdf = @"K:\new.pdf";   
try   
{   
    DuoDimension.HtmlToPdf conv = new DuoDimension.HtmlToPdf();   
    conv.OpenHTML(file_html);   
    conv.SavePDF(file_pdf);   
    textBox4.Text = "C# Example: Converting succeeded";   
}   

Info + c# /VB的例子,你可以在:http://www.duodimension.com/html_pdf_asp.net/component_html_pdf.aspx找到

我之前也在找这个。我遇到了HTMLDOC http://www.easysw.com/htmldoc/,这是一个免费的开源命令行应用程序,它以HTML文件为参数,并从中输出PDF。这在我的副业项目中非常有效,但这完全取决于你真正需要什么。

制作它的公司出售编译后的二进制文件,但您可以免费从源代码下载和编译并使用它。我设法编译了一个最近的版本(1.9版本),我打算在几天内发布它的二进制安装程序,所以如果你感兴趣,我可以在发布它时立即提供它的链接。

编辑(2/25/2014):看起来文档和网站转移到http://www.msweet.org/projects.php?Z1

最好的工具,我发现和用于生成javascript和样式渲染视图或html页面的PDF是phantomJS。

下载带有rasterize.js函数的.exe文件,在示例文件夹的exe根目录下找到,并放入解决方案。

它甚至允许你下载文件在任何代码,而不打开该文件,它也允许下载文件时,风格和特别是jquery应用。

以下代码生成PDF文件:

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;
}

编辑:新建议 使用PdfSharp的PDF HTML渲染器

(在尝试wkhtmltopdf并建议避免它之后)

HtmlRenderer。PdfSharp是一个100%完全c#托管代码,易于使用,线程安全,最重要的是免费(新BSD许可证)的解决方案。

使用

下载HtmlRenderer。PdfSharp nuget包。 使用实例方法。 public static Byte[] PdfSharpConvert(String html) { 字节[]res = null; 使用(内存流ms =新的内存流()) { var pdf = TheArtOfDev.HtmlRenderer.PdfSharp.PdfGenerator。GeneratePdf (html、PdfSharp.PageSize.A4); pdf.Save(女士); res = ms.ToArray(); } 返回res; }

一个非常好的替代是iTextSharp的免费版本

在版本4.1.6之前,iTextSharp是在LGPL许可下授权的,而4.16之前的版本(或者也可能有分叉)是作为包提供的,可以自由使用。当然有人可以使用5+付费版本。

我尝试在我的项目中集成wkhtmltopdf解决方案,遇到了一堆障碍。

我个人会避免在托管企业应用程序上使用基于wkhtmltopdf的解决方案,原因如下。

First of all wkhtmltopdf is C++ implemented not C#, and you will experience various problems embedding it within your C# code, especially while switching between 32bit and 64bit builds of your project. Had to try several workarounds including conditional project building etc. etc. just to avoid "invalid format exceptions" on different machines. If you manage your own virtual machine its ok. But if your project is running within a constrained environment like (Azure (Actually is impossible withing azure as mentioned by the TuesPenchin author) , Elastic Beanstalk etc) it's a nightmare to configure that environment only for wkhtmltopdf to work. wkhtmltopdf is creating files within your server so you have to manage user permissions and grant "write" access to where wkhtmltopdf is running. Wkhtmltopdf is running as a standalone application, so its not managed by your IIS application pool. So you have to either host it as a service on another machine or you will experience processing spikes and memory consumption within your production server. It uses temp files to generate the pdf, and in cases Like AWS EC2 which has really slow disk i/o it is a big performance problem. The most hated "Unable to load DLL 'wkhtmltox.dll'" error reported by many users.

——PRE编辑部分——

对于任何想要在更简单的应用程序/环境中从html生成pdf的人,我把我的旧帖子作为建议。

TuesPechkin

https://www.nuget.org/packages/TuesPechkin/

或专为MVC Web应用程序 (但我认为你可以在任何。net应用程序中使用它)

旋转

https://www.nuget.org/packages/Rotativa/

他们都利用了 Wkhtmtopdf二进制转换HTML到pdf。它使用webkit引擎来呈现页面,因此它也可以解析css样式表。

它们提供了易于使用的与c#的无缝集成。

Rotativa还可以从任何Razor View直接生成pdf。

此外,对于现实世界的web应用程序,他们还管理线程安全等…