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

有没有更好的办法?


当前回答

最好的工具,我发现和用于生成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;
}

其他回答

最后更新: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

很可能大多数项目将包装C/ c++引擎,而不是从头开始实现c#解决方案。试试哥德堡计划。

为了测试它

docker run --rm -p 3000:3000 thecodingmachine/gotenberg:6

旋度样本

curl --request POST \
    --url http://localhost:3000/convert/url \
    --header 'Content-Type: multipart/form-data' \
    --form remoteURL=https://brave.com \
    --form marginTop=0 \
    --form marginBottom=0 \
    --form marginLeft=0 \
    --form marginRight=0 \
    -o result.pdf

c# sample.cs

using System;
using System.Net.Http;
using System.Threading.Tasks;
using System.IO;
using static System.Console;

namespace Gotenberg
{
    class Program
    {
        public static async Task Main(string[] args)
        {
            try
            {
                var client = new HttpClient();            
                var formContent = new MultipartFormDataContent
                    {
                        {new StringContent("https://brave.com/"), "remoteURL"},
                        {new StringContent("0"), "marginTop" }
                    };
                var result = await client.PostAsync(new Uri("http://localhost:3000/convert/url"), formContent);
                await File.WriteAllBytesAsync("brave.com.pdf", await result.Content.ReadAsByteArrayAsync());
            }
            catch (Exception ex)
            {
                WriteLine(ex);
            }
        }
    }
}

要编译

csc sample.cs -langversion:latest -reference:System.Net.Http.dll && mono ./sample.exe

HTML到PDF的转换大多依赖于IE来完成HTML的解析和渲染。这可以打破用户更新他们的IE。这里有一个不依赖IE的。

代码是这样的:

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

像许多其他转换器一样,您可以传递文本、文件名或Url。结果可以保存到文件或流中。

PDFmyURL最近也发布了一个。net组件,用于网页/ HTML到PDF的转换。它有一个非常友好的用户界面,例如:

PDFmyURL pdf = new PDFmyURL("yourlicensekey");
pdf.ConvertURL("http://www.example.com", Application.StartupPath + @"\example.pdf");

文档:PDFmyURL .NET组件文档

免责声明:我为拥有PDFmyURL的公司工作

到目前为止,似乎最好的免费。net解决方案是TuesPechkin库,它是wkhtmltopdf本机库的包装。

我现在已经使用单线程版本将几千个HTML字符串转换为PDF文件,它似乎工作得很好。它应该也可以在多线程环境中工作(例如IIS),但我还没有对此进行测试。

另外,因为我想使用最新版本的wkhtmltopdf(在编写时为0.12.5),我从官方网站下载了DLL,复制到我的项目根目录,设置copy to output为true,并像这样初始化库:

var dllDir = AppDomain.CurrentDomain.BaseDirectory;
Converter = new StandardConverter(new PdfToolset(new StaticDeployment(dllDir)));

上面的代码看起来完全是“wkhtmltox.dll”,所以不要重命名文件。我使用的是64位版本的DLL。

确保你阅读了多线程环境的说明,因为你只需要在每个应用生命周期中初始化它一次,所以你需要把它放在一个单例或其他东西中。