C# 将数据表转换为 PDF
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13927675/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Convert Datatable to PDF
提问by Rajaram Shelar
采纳答案by MahaSwetha
Using iTextSharp,you can do it.It can be download from internet and it is free. Please, find the code below,
使用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();
}
回答by TODOName
You can't "convert" a DataTableto a PDF Document. But you can insertdata into it as normal content.
您不能将a转换DataTable为 PDF 文档。但是您可以将数据作为普通内容插入其中。
This would have to be done through a data control, like the GridViewor ListView; just like in a normal webpage. Which is why the articleyou have linked to does that. GridViewis 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.
这必须通过数据控件来完成,例如GridViewor ListView; 就像在普通网页中一样。这就是您链接到的文章这样做的原因。GridView可能是使它在美学上与DataTable. 因为它只会作为普通表格存储在 PDF 文档中。
Note that the GridViewis 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.
请注意,GridView是在内存中创建的 - 您不需要在 HTML 页面中创建或需要有一个。尝试和试验代码以更好地理解这一点。
So I recommend following the article.
所以我建议关注这篇文章。

