Export html to pdf in ASP.NET

2019-04-01 19:02发布

问题:

I am trying to export retrieved data from SQL into PDF using ASP.NET (C#). Remarks:

  1. I am not using a gridview.
  2. I designed the format of the page by using an HTML table and asp labels.
    • HTML table to format the layout and asp labels to show the values of my selected data from SQL.

How can I convert an HTML table to PDF using ASP.NET?

Can anyone help me? Thanks.

回答1:

You can try to use itextsharp (link)

Example:

using iTextSharp.text;
using iTextSharp.text.pdf;
using System.IO;
using iTextSharp.text.html;

// step 1 -- get html content
string htmlContent = ... // you html code (for example table from your page)

Document document = new Document();

// step 2:
// we create a writer that listens to the document
// and directs a PDF-stream to a file
PdfWriter.GetInstance(document, new FileStream("c:\\Chap0101.pdf", FileMode.Create));

// step 3: we open the document
document.Open();

// step 4: we add a paragraph to the document
//document.Add(new Paragraph(htmlContent.ToString()));

System.Xml.XmlTextReader _xmlr = new System.Xml.XmlTextReader(new StringReader(htmlContent));

HtmlParser.Parse(document, _xmlr);

// step 5: we close the document
document.Close();


回答2:

You can use ExpertPdf (www.html-to-pdf.net). It's an html to pdf converter I've been using with great success lately.



回答3:

There is a distinction to be made between solutions that accept HTML style content and those that accept real world HTML.

Solutions that accept HTML style or a subset of HTML are fairly small and self contained. However it is important that you have completely control over the HTML you're going to be using so that you can ensure that your content conforms to the capabilities of your solution. The iText XmlTextReader is an example of this.

Other solutions work based on real world HTML and real world browser technologies for proper HTML/CSS/SVG/ etc etc etc support. Our ABCpdf .NET product is an example of this - it includes both a Gecko (FireFox) style layout engine and a Trident (IE - like) engine.

Which you prefer is very much dependent on how much control you have over your source content.



回答4:

I use wkhtmltopdf, a command line application you can call from ASP.NET.