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

有没有更好的办法?


当前回答

如果你已经使用itextsharp dll,不需要添加第三方dll的(插件),我认为你正在使用htmlworker而不是它使用xmlworker,你可以很容易地将你的html转换为pdf。 一些css不能工作,他们是受支持的css 完整的解释与示例参考点击这里

        MemoryStream memStream = new MemoryStream();
        TextReader xmlString = new StringReader(outXml);
        using (Document document = new Document())
        {
            PdfWriter writer = PdfWriter.GetInstance(document, memStream);
            //document.SetPageSize(iTextSharp.text.PageSize.A4);
            document.Open();
            byte[] byteArray = System.Text.Encoding.UTF8.GetBytes(outXml);
            MemoryStream ms = new MemoryStream(byteArray);
            XMLWorkerHelper.GetInstance().ParseXHtml(writer, document, ms, System.Text.Encoding.UTF8);
            document.Close();
        }

        Response.ContentType = "application/pdf";
        Response.AddHeader("content-disposition", "attachment;filename=" + filename + ".pdf");
        Response.Cache.SetCacheability(HttpCacheability.NoCache);
        Response.BinaryWrite(memStream.ToArray());
        Response.End();
        Response.Flush();

其他回答

很可能大多数项目将包装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。结果可以保存到文件或流中。

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

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

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

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

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

编辑:新建议 使用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应用程序,他们还管理线程安全等…