【问题标题】:How can we export datatable to PDF using iTextSharp?我们如何使用 iTextSharp 将数据表导出为 PDF?
【发布时间】:2015-08-11 04:48:04
【问题描述】:

我们如何在 C# 中使用 iTextSharp 将数据表导出为 PDF?

public void ExportToPdf(DataTable dt)
   {      
    Document document = new Document();
    PdfWriter writer = PdfWriter.GetInstance(document, new FileStream("c://sample.pdf", FileMode.Create));
    document.Open();
    PdfPTable table = new PdfPTable(dt.Columns.Count);
    PdfPRow row = null;
    float[] widths = new float[] { 2f, 2f, 2f, 2f };
    table.SetWidths(widths);
    table.WidthPercentage = 100;
    PdfPCell cell = new PdfPCell(new Phrase("Products"));
    cell.Colspan = dt.Columns.Count; 
}

【问题讨论】:

    标签: c# itextsharp export-to-pdf


    【解决方案1】:

    这里是示例代码。请检查这个。

    public void ExportToPdf(DataTable dt)
       {      
        Document document = new Document();
        PdfWriter writer = PdfWriter.GetInstance(document, new FileStream("c://sample.pdf", FileMode.Create));
        document.Open();
                iTextSharp.text.Font font5 = iTextSharp.text.FontFactory.GetFont(FontFactory.HELVETICA, 5);
    
        PdfPTable table = new PdfPTable(dt.Columns.Count);
        PdfPRow row = null;
        float[] widths = new float[] { 4f, 4f, 4f, 4f };
    
        table.SetWidths(widths);
    
        table.WidthPercentage = 100;
        int iCol = 0;
        string colname = "";
        PdfPCell cell = new PdfPCell(new Phrase("Products"));
    
        cell.Colspan = dt.Columns.Count;
    
        foreach (DataColumn c in dt.Columns)
        {
    
            table.AddCell(new Phrase(c.ColumnName, font5));
        }
    
        foreach (DataRow r in dt.Rows)
        {
            if (dt.Rows.Count > 0)
            {
                table.AddCell(new Phrase(r[0].ToString(), font5));
                table.AddCell(new Phrase(r[1].ToString(), font5));
                table.AddCell(new Phrase(r[2].ToString(), font5));
                table.AddCell(new Phrase(r[3].ToString(), font5));
            }          
        }  document.Add(table);
            document.Close();
    }
    

    【讨论】:

    • 如果您追求速度,这是更好的解决方案。 @vakeel 的另一个答案要求您首先将数据转换为 HTML,并且只有在完全创建 HTML 时才开始创建 PDF。对于大型数据集,这会严重降低您的应用程序速度。而且,另一个答案使用了HTMLWorker,一个已经被废弃的类。
    • 这个解决方案对 iText7 有效吗?
    【解决方案2】:

    这是更笼统的。它适用于任何 DataTable

    public void createPDF(DataTable dataTable, string destinationPath)
    {
        Document document = new Document();
        PdfWriter writer = PdfWriter.GetInstance(document, new FileStream(destinationPath, FileMode.Create));
        document.Open();
    
        PdfPTable table = new PdfPTable(dataTable.Columns.Count);
        table.WidthPercentage = 100;
    
        //Set columns names in the pdf file
        for(int k = 0; k < dataTable.Columns.Count; k++)
        {
            PdfPCell cell = new PdfPCell(new Phrase(dataTable.Columns[k].ColumnName));
    
            cell.HorizontalAlignment = PdfPCell.ALIGN_CENTER;
            cell.VerticalAlignment = PdfPCell.ALIGN_CENTER;
            cell.BackgroundColor = new iTextSharp.text.BaseColor(51, 102, 102);
    
            table.AddCell(cell);
        }
    
        //Add values of DataTable in pdf file
        for(int i = 0; i < dataTable.Rows.Count; i++)
        {
            for(int j = 0; j < dataTable.Columns.Count; j++)
            {
                PdfPCell cell = new PdfPCell(new Phrase(dataTable.Rows[i][j].ToString()));
    
                //Align the cell in the center
                cell.HorizontalAlignment = PdfPCell.ALIGN_CENTER;
                cell.VerticalAlignment = PdfPCell.ALIGN_CENTER;
    
                table.AddCell(cell);
            }
        }
    
        document.Add(table);
        document.Close();
    }
    

    【讨论】:

      【解决方案3】:

      首先在 ASP.Net 中导入 iTextSharp 库。

      HTML 标记

      HTML 标记包含一个用于生成 PDF 的按钮

      <asp:Button Text="Generate Invoice" OnClick="GenerateInvoicePDF" runat="server" />
      

      C#

      using System.IO;
      using System.Text;
      using System.Data;
      using iTextSharp.text;
      using iTextSharp.text.pdf;
      using iTextSharp.text.html.simpleparser;
      
      protected void GenerateInvoicePDF(object sender, EventArgs e)
      {
          //Dummy data for Invoice (Bill).
          string companyName = "ASPSnippets";
          int orderNo = 2303;
          DataTable dt = new DataTable();
          dt.Columns.AddRange(new DataColumn[5] {
                                  new DataColumn("ProductId", typeof(string)),
                                  new DataColumn("Product", typeof(string)),
                                  new DataColumn("Price", typeof(int)),
                                  new DataColumn("Quantity", typeof(int)),
                                  new DataColumn("Total", typeof(int))});
          dt.Rows.Add(101, "Sun Glasses", 200, 5, 1000);
          dt.Rows.Add(102, "Jeans", 400, 2, 800);
          dt.Rows.Add(103, "Trousers", 300, 3, 900);
          dt.Rows.Add(104, "Shirts", 550, 2, 1100);
      
          using (StringWriter sw = new StringWriter())
          {
              using (HtmlTextWriter hw = new HtmlTextWriter(sw))
              {
                  StringBuilder sb = new StringBuilder();
      
                  //Generate Invoice (Bill) Header.
                  sb.Append("<table width='100%' cellspacing='0' cellpadding='2'>");
                  sb.Append("<tr><td align='center' style='background-color: #18B5F0' colspan = '2'><b>Order Sheet</b></td></tr>");
                  sb.Append("<tr><td colspan = '2'></td></tr>");
                  sb.Append("<tr><td><b>Order No: </b>");
                  sb.Append(orderNo);
                  sb.Append("</td><td align = 'right'><b>Date: </b>");
                  sb.Append(DateTime.Now);
                  sb.Append(" </td></tr>");
                  sb.Append("<tr><td colspan = '2'><b>Company Name: </b>");
                  sb.Append(companyName);
                  sb.Append("</td></tr>");
                  sb.Append("</table>");
                  sb.Append("<br />");
      
                  //Generate Invoice (Bill) Items Grid.
                  sb.Append("<table border = '1'>");
                  sb.Append("<tr>");
                  foreach (DataColumn column in dt.Columns)
                  {
                      sb.Append("<th style = 'background-color: #D20B0C;color:#ffffff'>");
                      sb.Append(column.ColumnName);
                      sb.Append("</th>");
                  }
                  sb.Append("</tr>");
                  foreach (DataRow row in dt.Rows)
                  {
                      sb.Append("<tr>");
                      foreach (DataColumn column in dt.Columns)
                      {
                          sb.Append("<td>");
                          sb.Append(row[column]);
                          sb.Append("</td>");
                      }
                      sb.Append("</tr>");
                  }
                  sb.Append("<tr><td align = 'right' colspan = '");
                  sb.Append(dt.Columns.Count - 1);
                  sb.Append("'>Total</td>");
                  sb.Append("<td>");
                  sb.Append(dt.Compute("sum(Total)", ""));
                  sb.Append("</td>");
                  sb.Append("</tr></table>");
      
                  //Export HTML String as PDF.
                  StringReader sr = new StringReader(sb.ToString());
                  Document pdfDoc = new Document(PageSize.A4, 10f, 10f, 10f, 0f);
                  HTMLWorker htmlparser = new HTMLWorker(pdfDoc);
                  PdfWriter writer = PdfWriter.GetInstance(pdfDoc, Response.OutputStream);
                  pdfDoc.Open();
                  htmlparser.Parse(sr);
                  pdfDoc.Close();
                  Response.ContentType = "application/pdf";
                  Response.AddHeader("content-disposition", "attachment;filename=Invoice_" + orderNo + ".pdf");
                  Response.Cache.SetCacheability(HttpCacheability.NoCache);
                  Response.Write(pdfDoc);
                  Response.End();
              }
          }
      }
      

      参考:http://www.aspsnippets.com/Articles/Generate-Invoice-Bill-Receipt-PDF-from-database-in-ASPNet-using-C-and-VBNet.aspx

      【讨论】:

      • 这个答案使用HTMLWorkerHTMLWorker 已被 XMLWorker 弃用。如果您的数据集很小,创建 HTML 然后使用 XML Worker 将其转换为 PDF 可能是可以接受的。如果您有一个大型数据集,这种方法将对您的内存和 CPU 使用产生严重影响。在这种情况下,@Nakala 的答案是更好的解决方案。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-08-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多