C# 从原始 HTML/CSS 内容从 ASP.NET 生成 PDF?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/570179/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-04 08:38:48  来源:igfitidea点击:

Generate PDF from ASP.NET from raw HTML/CSS content?

c#asp.nethtmlpdf

提问by

I'm sending emails that have invoices attached as PDFs. I'm already - elsewhere in the application - creating the invoices in an .aspx page. I'd like to use Server.Execute to return the output HTML and generate a PDF from that. Otherwise, I'd have to use a reporting tool to "draw" the invoice on a PDF. That blows for lots of reasons, not the least of which is that I'd have to update both the .aspx page and the report for every minor change. What to do...

我正在发送附有 PDF 格式发票的电子邮件。我已经 - 在应用程序的其他地方 - 在 .aspx 页面中创建发票。我想使用 Server.Execute 返回输出 HTML 并从中生成 PDF。否则,我将不得不使用报告工具在 PDF 上“绘制”发票。这有很多原因,其中最重要的是我必须为每个小的更改更新 .aspx 页面和报告。该怎么办...

采纳答案by

There is no way to generate a PDF from an HTML string directly within .NET, but there are number of third party controls that work well.

无法在 .NET 中直接从 HTML 字符串生成 PDF,但有许多第三方控件可以很好地工作。

I've had success with this one: http://www.html-to-pdf.netand this: http://www.htmltopdfasp.net

我在这个方面取得了成功:http: //www.html-to-pdf.net和这个:http: //www.htmltopdfasp.net

The important questions to ask are:

要问的重要问题是:

  1. Does it render correctly as compared to the 3 major browsers: IE, FF and Safari/Chrome?
  2. Does it handle CSS fine?
  3. Does the control have it's own rendering engine? If so, bounce it. You don't want to trust a home grown rendering engine - the browsers have a hard enough problem getting everything pixel perfect.
  4. What dependencies does the third party control require? The fewer, the better.
  1. 与 IE、FF 和 Safari/Chrome 3 种主要浏览器相比,它是否能正确呈现?
  2. 它可以很好地处理 CSS 吗?
  3. 控件是否有自己的渲染引擎?如果是这样,请弹跳它。你不想相信一个自制的渲染引擎——浏览器有一个足够困难的问题,让所有的像素都完美。
  4. 第三方控件需要哪些依赖?越少越好。

There are a few others but they deal with ActiveX displays and such.

还有其他一些,但它们处理 ActiveX 显示等。

回答by marc_s

As long as you can make sure to use proper XHTML, you could also use a product like Alt-Soft's Xml2PDFto convert XML (XHTML) into PDF by means of XSLT/XSL-FO.

只要您能确保使用正确的XHTML,您也可以使用Alt-Soft 的Xml2PDF 之类的产品通过XSLT/XSL-FO 将XML (XHTML) 转换为PDF。

It takes a bit of a learning curve to master, but it works very well once you've "got" it!

掌握它需要一些学习曲线,但是一旦“掌握”它,它就会非常有效!

Marc

马克

回答by marc_s

We use a product called ABCPDF for this and it works fantastic.

我们为此使用了一种名为 ABCPDF 的产品,它的效果非常好。

http://www.websupergoo.com/abcpdf-1.htm

http://www.websupergoo.com/abcpdf-1.htm

回答by crb

This sounds like a job for Prince. It can take HTML and CSS and generate a PDF, which you can then present to your users. It supports CSS3 better than most web browsers (staff include H?kon Wium Lie, the inventor of CSS).

这听起来像是普林斯的工作。它可以采用 HTML 和 CSS 并生成 PDF,然后您可以将其呈现给您的用户。它比大多数网络浏览器更好地支持 CSS3(工作人员包括 CSS 的发明者 H?kon Wium Lie)。

See the samples, especially the ones for Wikipedia pages, for the beautiful output it can generate. There's also an interesting Google Tech Talkwith the authors.

查看示例,尤其是 Wikipedia 页面的示例,了解它可以生成的漂亮输出。还有一个有趣的谷歌技术谈话与作者。

Edit:There is a .NET wrapperavailable.

编辑:有一个.NET 包装器可用。

回答by Gregory A Beamer

Since you are producing the answer, you can use a tool like Report.NET: http://sourceforge.net/projects/report/

由于您正在生成答案,您可以使用 Report.NET 之类的工具:http: //sourceforge.net/projects/report/

I disagree with the answers that say you cannot convert directly from output to PDF, however, as you can "re-call" the page and get the HTML as a stream and convert it. I am not sure what tool you would want to use to do this, however. In other words, it is possible, but I am not sure it is worth it. The PDF creation libs, like Report.NET, even though they force reusing some logic and no automagic converrsion, it is easier.

但是,我不同意无法直接从输出转换为 PDF 的答案,因为您可以“重新调用”页面并将 HTML 作为流获取并进行转换。但是,我不确定您想使用什么工具来执行此操作。换句话说,这是可能的,但我不确定是否值得。PDF 创建库,如 Report.NET,尽管它们强制重用某些逻辑并且没有自动转换,但它更容易。

I have not tried this component, but I have heard good things about it from those who have. The model is more like HTML, but I am not sure you can simply send a rendered ASPX to it to create PDF: http://www.websupergoo.com/abcpdf-8.htm

我还没有尝试过这个组件,但我从那些尝试过的人那里听到了关于它的好消息。该模型更像是 HTML,但我不确定您是否可以简单地向其发送渲染的 ASPX 以创建 PDF:http: //www.websupergoo.com/abcpdf-8.htm

回答by Gregory A Beamer

I'd go a different route. Assuming you are using SQL Server, use SSRS and generate the PDF that way.

我会走不同的路线。假设您使用的是 SQL Server,请使用 SSRS 并以这种方式生成 PDF。

回答by Constantine

If you try to find some html to pdf software via GOOGLEyou'll get a pile of this stuff. There are about 10 leaders but most of them use IE dlls in background mode. Just couple of them use their own parsing engine. Please try PDF Duo .NETcomponent in your ASP.NET project if you wish to create a PDF programaticaly. It is light component for a cool generating of PDF invoces, reports e.g.

如果你试图通过GOOGLE找到一些 html 到 pdf 的软件,你会得到一堆这样的东西。大约有 10 个领导者,但他们中的大多数在后台模式下使用 IE dll。他们中只有几个人使用自己的解析引擎。如果您希望以编程方式创建 PDF,请在您的 ASP.NET 项目中尝试PDF Duo .NET组件。它是一个很酷的生成 PDF 调用的轻量级组件,报告例如

回答by c-sharp

wkhtmltopdfis a free and cool exe to generate pdf from html. Its written in c++. But nReco htmltopdfis a wrapper dotnet library for this awesome tool. I implemented using this dotnet library and it was just so good it does everything by its own you just need to give html as a data source.

wkhtmltopdf是一个免费且很酷的 exe,用于从 html 生成 pdf。它是用 C++ 编写的。但是nReco htmltopdf是这个很棒的工具的包装 dotnet 库。我使用这个 dotnet 库实现了它,它非常好,它自己完成所有事情,您只需要提供 html 作为数据源。

/// <summary>
/// Converts html into PDF using nReco dll and wkhtmltopdf.exe.
/// </summary>       
private byte[] ConvertHtmlToPDF()
{
  HtmlToPdfConverter nRecohtmltoPdfObj = new HtmlToPdfConverter();
  nRecohtmltoPdfObj.Orientation = PageOrientation.Portrait;
  nRecohtmltoPdfObj.PageFooterHtml = CreatePDFFooter();
  nRecohtmltoPdfObj.CustomWkHtmlArgs = "--margin-top 35 --header-spacing 0 --margin-left 0 --margin-right 0";           
  return nRecohtmltoPdfObj.GeneratePdf(CreatePDFScript() + ShowHtml() + "</body></html>");
}

The above function is an excerpt from the below link post which explains it in detail. HTML to PDF in ASP.Net

上述功能摘自以下链接帖子,其中详细解释了它。 ASP.Net 中的 HTML 转 PDF

回答by EvoPdf

The initial question is about converting another aspx page containing an invoice to a PDF document. The invoice is probably using some session data and the user suggests to use Server.Execute()to obtain the invoice page HTML code and then to convert that code to PDF. Converting the invoice page URL directly is not possible because a new session would be created during conversion and the session data would be lost.

最初的问题是将另一个包含发票的 aspx 页面转换为 PDF 文档。发票可能正在使用一些会话数据,用户建议使用Server.Execute()获取发票页面 HTML 代码,然后将该代码转换为 PDF。直接转换发票页面 URL 是不可能的,因为转换期间会创建一个新会话并且会话数据会丢失。

This is actually a good technique to preserve session data during conversion which is applied in Convert a HTML Page to PDF in Same Session ASP.NET Demoof the EvoPdf library. The complete C# code to get the HTML string rendered by the invoice page and to convert that string to PDF is:

这实际上是一种在转换过程中保留会话数据的好技术,在 EvoPdf 库的同一会话 ASP.NET 演示中将HTML 页面转换为 PDF 中应用。获取发票页面呈现的 HTML 字符串并将该字符串转换为 PDF 的完整 C# 代码是:

// Execute the invoice page and get the HTML string rendered by this page
TextWriter outTextWriter = new StringWriter();
Server.Execute("Invoice.aspx", outTextWriter);

string htmlStringToConvert = outTextWriter.ToString();

// Create a HTML to PDF converter object with default settings
HtmlToPdfConverter htmlToPdfConverter = new HtmlToPdfConverter();

// Use the current page URL as base URL
string baseUrl = HttpContext.Current.Request.Url.AbsoluteUri;

// Convert the page HTML string to a PDF document in a memory buffer
byte[] outPdfBuffer = htmlToPdfConverter.ConvertHtml(htmlStringToConvert, baseUrl);

// Send the PDF as response to browser

// Set response content type
Response.AddHeader("Content-Type", "application/pdf");

// Instruct the browser to open the PDF file as an attachment or inline
Response.AddHeader("Content-Disposition", String.Format("attachment; filename=Convert_Page_in_Same_Session.pdf; size={0}", outPdfBuffer.Length.ToString()));

// Write the PDF document buffer to HTTP response
Response.BinaryWrite(outPdfBuffer);

// End the HTTP response and stop the current page processing
Response.End();

回答by Winnovative

A possible minimal solution to use Server.Execute() to obtain the HTML of the invoice page and convert that code to a PDF using winnovative html to pdf api for .netis:

使用 Server.Execute() 获取发票页面的 HTML 并使用winnovative html to pdf api for .net将该代码转换为 PDF 的一个可能的最小解决方案是:

TextWriter outTextWriter = new StringWriter();
Server.Execute("Invoice.aspx", outTextWriter);

HtmlToPdfConverter htmlToPdfConverter = new HtmlToPdfConverter();

byte[] pdfBytes = htmlToPdfConverter.ConvertHtml(outTextWriter.ToString(),
            httpContext.Current.Request.Url.AbsoluteUri);