我正在使用itextsharp v 5.5.13创建PDF文档。
我需要帮助的一种情况是PDF文档具有结构(页眉,正文和页脚,如模板)。这个想法是只在正文部分填充数据。每当下一页有数据溢出时,数据就会进入下一页的正文,并保持相同的结构(即具有页眉和页脚)。
当前,我可以通过创建pageeventhelper来达到相同的目的,其中在页面的开始和页面结束处添加页眉和页脚。通过这种方法,我能够获得所需的结果,但是看起来有点不客气,并且外观也不是那么好(空白,空白等)。
关于处理此用例的更好方法的任何建议吗?
代码如下所示,
在PdfPageEventHelper中,我有两个不同的页眉分别位于第1页和第2页,以及一个页脚,
protected PdfPTable primaryHeader;
protected PdfPTable secondaryHeader;
protected PdfPTable footer;
public void setPrimaryHeader(PdfPTable header)
{
this.primaryHeader = header;
}
public void setSecondaryHeader(PdfPTable header)
{
this.secondaryHeader = header;
}
public void setFooter(PdfPTable footer)
{
this.footer = footer;
}
public override void OnStartPage(PdfWriter writer, Document document)
{
base.OnStartPage(writer, document);
if (writer.PageNumber == 1)
{
this.primaryHeader.TotalWidth = document.Right - document.Left;
this.primaryHeader.WriteSelectedRows(0, -1, 10, document.Top + 40, writer.DirectContent);
// Adding extra space to remove overlap of text
document.Add(PdfHelper.GetEmptyTable(200f));
}
else
{
this.secondaryHeader.TotalWidth = document.Right - document.Left;
this.secondaryHeader.WriteSelectedRows(0, -1, 10, document.Top + 40, writer.DirectContent);
// Adding extra space to remove overlap of text
document.Add(PdfHelper.GetEmptyTable(60f));
}
}
public override void OnEndPage(PdfWriter writer, Document document)
{
base.OnEndPage(writer, document);
this.footer.TotalWidth = document.Right - document.Left;
this.footer.WriteSelectedRows(0, -1, 10, document.Bottom + 10, writer.DirectContent);
}
以下代码创建字节数组pdf,
using (MemoryStream stream = new MemoryStream())
{
Document document = new Document(PageSize.A4, 10, 10, 42, 35);
PdfWriter writer = PdfWriter.GetInstance(document, stream);
CustomPageEventHelper peh = new CustomPageEventHelper(true);
peh.setPrimaryHeader(GetPrimaryHeader(response, identity));
peh.setSecondaryHeader(GetSecondaryHeader(response, identity));
peh.setFooter(GetFooter(response, identity));
writer.PageEvent = peh;
document.Open();
PdfPTable table = null;
PdfPTable tableOuter = null;
PdfPTable tableInner = null;
PdfPTable tableGrid = null;
PdfPCell cell = null;
// Adding content here via PdfPTable's
document.Close();
result = stream.ToArray();
}