Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
202 views
in Technique[技术] by (71.8m points)

c# - Convert Datatable to PDF

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 this article but it is using gridview for exporting

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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();
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...