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

25,923

Solution 1

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.

I've had success with this one: http://www.html-to-pdf.net and this: 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.

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

Solution 2

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

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

Solution 3

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).

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

Edit: There is a .NET wrapper available.

Solution 4

wkhtmltopdf is a free and cool exe to generate pdf from html. Its written in c++. But nReco htmltopdf is 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.

/// <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

Solution 5

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.

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 Demo of 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:

// 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();
Share:
25,923
Admin
Author by

Admin

Updated on July 20, 2022

Comments

  • Admin
    Admin almost 2 years

    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...

  • Admin
    Admin about 15 years
    This product looks good, but it isn't really built well to be packaged with a .NET application. Looks like they have a .dll you can wrap at least.
  • crb
    crb about 15 years
    I can't say I've tried - I've used it with MindTouch Deki, which calls the .exe directly. What I can say is the output is gorgeous - it's more like LaTeX than CutePDF from Internet Explorer :)
  • Levitikon
    Levitikon over 12 years
    Not digging the logo they tack onto the first page of every document
  • crb
    crb over 12 years
    Paid versions of Prince do not have the logo.
  • Rebecca
    Rebecca over 8 years
    US$3800 Server license!
  • Rebecca
    Rebecca over 8 years
    Site license: US$1170
  • Rebecca
    Rebecca over 8 years
    Standard license: US$1,495
  • marc_s
    marc_s over 8 years
    @Junto: yes - so - creating software costs money - so the tool aren't all just FREE - but there IS a free Xml2Pdf Workstation version, too
  • Rebecca
    Rebecca over 8 years
    @marc-s Of course it costs money, but it also doesn't hurt to disclose that this is a paid product and the standard license is required to generate PDFs from HTML content.
  • Sen Alexandru
    Sen Alexandru about 3 years
    NReco.LT (for .NET Core) is a paid package and requires a commercial license