我们如何使用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;
}
答案 0 :(得分:8)
以下是示例代码。请检查一下。
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();
}
答案 1 :(得分: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();
}
答案 2 :(得分:0)
首先在ASP.Net中导入iTextSharp库。
HTML标记
HTML标记包含一个生成PDF的按钮
$tagline.css({
'top' : -(windowScroll/3)+"px",
'webkit-transition-property': 'top',
'webkit-transition-duration': '.5s'
});
<强> C#强>
<asp:Button Text="Generate Invoice" OnClick="GenerateInvoicePDF" runat="server" />