12

我可以在 Asp.net Web 应用程序中获取将数据表转换为 pdf 的代码吗?我想要具有导出datatablePDF. 我找到了这篇文章,但它gridview用于导出

4

2 回答 2

28

使用 iTextSharp,你可以做到。它可以从互联网上下载,它是免费的。请找到下面的代码,

   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();
}
于 2012-12-18T06:53:04.487 回答
5

您不能将 a“转换DataTable为 PDF 文档。但是您可以数据作为普通内容插入其中。

This would have to be done through a data control, like the GridView or ListView; just like in a normal webpage. Which is why the article you have linked to does that. GridView is probably the closest and easiest way to make it aesthetically appear the same as a DataTable. As it will just be stored as a normal table in the PDF Document.

Note that the GridView is created in memory - you don't create or need to have one in your HTML page. Try and experiment with the code to understand this better.

So I recommend following the article.

于 2012-12-18T07:01:04.677 回答