我在 asp.net c# 中使用 iTextSharp 5.3.5 版从我的 DataTable 生成 PDF。我的 DataTable 包含未知行,sp 而 PDF 生成如果它需要超过一页我需要为每页修复一些页眉和页脚
代码:
public DataTable dataTable;
protected void Page_Load(object sender, EventArgs e)
{
dataTable = getData();
Document document = new Document(PageSize.A4, 10, 10, 90, 10);
string path = Server.MapPath("PDFs");
PdfWriter writer = PdfWriter.GetInstance(document, new FileStream(path + "/Doc103.pdf", FileMode.Create));
document.Open();
CreatePages(document);
document.Close();
}
private void CreatePages(Document document)
{
document.NewPage();
document.Add(FormatPageHeaderPhrase(dataTable.TableName));
PdfPTable pdfTable = new PdfPTable(dataTable.Columns.Count);
pdfTable.DefaultCell.Padding = 3;
pdfTable.WidthPercentage = 100; // percentage
pdfTable.DefaultCell.BorderWidth = 2;
pdfTable.DefaultCell.HorizontalAlignment = Element.ALIGN_CENTER;
foreach (DataColumn column in dataTable.Columns)
{
pdfTable.AddCell(column.ColumnName);
}
pdfTable.HeaderRows = 1;
pdfTable.DefaultCell.BorderWidth = 1;
foreach (DataRow row in dataTable.Rows)
{
foreach (object cell in row.ItemArray)
{
pdfTable.AddCell(cell.ToString());
}
}
document.Add(pdfTable);
}
private static Phrase FormatPageHeaderPhrase(string value)
{
return new Phrase(value, FontFactory.GetFont(FontFactory.TIMES, 10, Font.BOLD, new BaseColor(255, 0, 0)));
}
PDF截图: