在我的应用程序中,我正在将数据表数据导出到pdf,它的工作正常,我现在想要添加页眉和页脚,我还要为它添加页码,我还希望页眉包含名称作为报告这页纸。我怎么能这样做?
我写了这样的代码:
public void ExportToPdf(DataTable ExDataTable)
{
//Here set page size as A4
Document pdfDoc = new Document(PageSize.A4, 10, 10, 10, 10);
try
{
PdfWriter.GetInstance(pdfDoc, System.Web.HttpContext.Current.Response.OutputStream);
pdfDoc.Open();
//Set Font Properties for PDF File
Font fnt = FontFactory.GetFont("Times New Roman", 6);
DataTable dt = ExDataTable;
if (dt != null)
{
PdfPTable PdfTable = new PdfPTable(dt.Columns.Count);
PdfPCell PdfPCell = null;
//Here we create PDF file tables
for (int rows = 0; rows < dt.Rows.Count; rows++)
{
if (rows == 0)
{
for (int column = 0; column < dt.Columns.Count; column++)
{
PdfPCell = new PdfPCell(new Phrase(new Chunk(dt.Columns[column].ColumnName.ToString(), fnt)));
PdfTable.AddCell(PdfPCell);
}
}
for (int column = 0; column < dt.Columns.Count; column++)
{
PdfPCell = new PdfPCell(new Phrase(new Chunk(dt.Rows[rows][column].ToString(), fnt)));
PdfTable.AddCell(PdfPCell);
}
}
// Finally Add pdf table to the document
pdfDoc.Add(PdfTable);
}
pdfDoc.Close();
Response.ContentType = "application/pdf";
//Set default file Name as current datetime
Response.AddHeader("content-disposition", "attachment; filename=" + "Line-Shift Report" + ".pdf");
System.Web.HttpContext.Current.Response.Write(pdfDoc);
Response.Flush();
Response.End();
}
catch (Exception ex)
{
Response.Write(ex.ToString());
}
}
protected void Button1_Click1(object sender, EventArgs e)
{
if (Session["source_table"] != null)
{
ExportToPdf(Session["source_table"] as DataTable);
}
else
{
Response.Write("No data to Export!");
}
}
有人可以帮我吗?
答案 0 :(得分:1)
创建新的页面事件类:
public class PageEvents : PdfPageEventHelper
{
public override void OnStartPage(PdfWriter writer, Document document)
{
base.OnStartPage(writer, document);
document.Add(...header...);
}
}
现在在你的代码中:
class Program
{
static void Main(string[] args)
{
using (var pdfDoc = new Document(...))
{
var pdfWriter = PdfWriter.GetInstance(pdfDoc, new FileStream("Test.pdf", FileMode.Create));
pdfWriter.PageEvent = new PageEvents();
....
答案 1 :(得分:0)
您必须为页眉和页脚创建pdftables。用标题图像/标题填充单元格。在页脚表中,你必须填写第4页的单元格。