Convert Datatable to PDF

后端 未结 2 2100
耶瑟儿~
耶瑟儿~ 2020-12-14 04:04

Can I get a code for converting datatable to pdf in Asp.net Web application. I want to have functionality to export datatable into PDF. I found t

2条回答
  •  长情又很酷
    2020-12-14 04:44

    Using iTextSharp,you can do it.It can be download from internet and it is free. Please, find the code below,

       public void ExportToPdf(DataTable dt,string strFilePath)
       {      
        Document document = new Document();
        PdfWriter writer = PdfWriter.GetInstance(document, new FileStream(strFilePath, 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[dt.Columns.Count];
        for (int i = 0; i < dt.Columns.Count; i++)
            widths[i] = 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)
            {
                for (int h = 0; h < dt.Columns.Count; h++)
                {
                    table.AddCell(new Phrase(r[h].ToString(), font5));
                }
            }          
        }
        document.Add(table);
        document.Close();
    }
    

提交回复
热议问题