Add Header and Footer for PDF using iTextsharp
How can I add header and footer for each page in the pdf.
Headed will contain just a text Footer will contain a text and pagination for pdf (Page : 1 of 4)
How is this possible ? I tried to add the below line, but header does not show up in pdf.
document.AddHeader("Header", "Header Text");
This the code I am using for generation PDF :
protected void GeneratePDF_Click(object sender, EventArgs e)
{
DataTable dt = getData();
Response.ContentType = "application/pdf";
Response.AddHeader("content-disposition", "attachment;filename=Locations.pdf");
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Document document = new Document();
PdfWriter.GetInstance(document, Response.OutputStream);
document.Open();
iTextSharp.text.Font font5 = iTextSharp.text.FontFactory.GetFont(FontFactory.COURIER , 8);
PdfPTable table = new PdfPTable(dt.Columns.Count);
PdfPRow row = null;
float[] widths = new float[] { 6f, 6f, 2f, 4f, 2f };
table.SetWidths(widths);
table.WidthPercentage = 100;
int iCol = 0;
string colname = "";
PdfPCell cell = new PdfPCell(new Phrase("Locations"));
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));
table.AddCell(new Phrase(r[4].ToString(), font5));
}
}
document.Add(table);
document.Close();
Response.Write(document);
Response.End();
}
}
As already answered by @Bruno you need to use pageEvents.
Please check out the sample code below:
private void CreatePDF()
{
string fileName = string.Empty;
DateTime fileCreationDatetime = DateTime.Now;
fileName = string.Format("{0}.pdf", fileCreationDatetime.ToString(@"yyyyMMdd") + "_" + fileCreationDatetime.ToString(@"HHmmss"));
string pdfPath = Server.MapPath(@"~\PDFs\") + fileName;
using (FileStream msReport = new FileStream(pdfPath, FileMode.Create))
{
//step 1
using (Document pdfDoc = new Document(PageSize.A4, 10f, 10f, 140f, 10f))
{
try
{
// step 2
PdfWriter pdfWriter = PdfWriter.GetInstance(pdfDoc, msReport);
pdfWriter.PageEvent = new Common.ITextEvents();
//open the stream
pdfDoc.Open();
for (int i = 0; i < 10; i++)
{
Paragraph para = new Paragraph("Hello world. Checking Header Footer", new Font(Font.FontFamily.HELVETICA, 22));
para.Alignment = Element.ALIGN_CENTER;
pdfDoc.Add(para);
pdfDoc.NewPage();
}
pdfDoc.Close();
}
catch (Exception ex)
{
//handle exception
}
finally
{
}
}
}
}
And create one class file named ITextEvents.cs and add following code:
public class ITextEvents : PdfPageEventHelper
{
// This is the contentbyte object of the writer
PdfContentByte cb;
// we will put the final number of pages in a template
PdfTemplate headerTemplate, footerTemplate;
// this is the BaseFont we are going to use for the header / footer
BaseFont bf = null;
// This keeps track of the creation time
DateTime PrintTime = DateTime.Now;
#region Fields
private string _header;
#endregion
#region Properties
public string Header
{
get { return _header; }
set { _header = value; }
}
#endregion
public override void OnOpenDocument(PdfWriter writer, Document document)
{
try
{
PrintTime = DateTime.Now;
bf = BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.NOT_EMBEDDED);
cb = writer.DirectContent;
headerTemplate = cb.CreateTemplate(100, 100);
footerTemplate = cb.CreateTemplate(50, 50);
}
catch (DocumentException de)
{
}
catch (System.IO.IOException ioe)
{
}
}
public override void OnEndPage(iTextSharp.text.pdf.PdfWriter writer, iTextSharp.text.Document document)
{
base.OnEndPage(writer, document);
iTextSharp.text.Font baseFontNormal = new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.HELVETICA, 12f, iTextSharp.text.Font.NORMAL, iTextSharp.text.BaseColor.BLACK);
iTextSharp.text.Font baseFontBig = new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.HELVETICA, 12f, iTextSharp.text.Font.BOLD, iTextSharp.text.BaseColor.BLACK);
Phrase p1Header = new Phrase("Sample Header Here", baseFontNormal);
//Create PdfTable object
PdfPTable pdfTab = new PdfPTable(3);
//We will have to create separate cells to include image logo and 2 separate strings
//Row 1
PdfPCell pdfCell1 = new PdfPCell();
PdfPCell pdfCell2 = new PdfPCell(p1Header);
PdfPCell pdfCell3 = new PdfPCell();
String text = "Page " + writer.PageNumber + " of ";
//Add paging to header
{
cb.BeginText();
cb.SetFontAndSize(bf, 12);
cb.SetTextMatrix(document.PageSize.GetRight(200), document.PageSize.GetTop(45));
cb.ShowText(text);
cb.EndText();
float len = bf.GetWidthPoint(text, 12);
//Adds "12" in Page 1 of 12
cb.AddTemplate(headerTemplate, document.PageSize.GetRight(200) + len, document.PageSize.GetTop(45));
}
//Add paging to footer
{
cb.BeginText();
cb.SetFontAndSize(bf, 12);
cb.SetTextMatrix(document.PageSize.GetRight(180), document.PageSize.GetBottom(30));
cb.ShowText(text);
cb.EndText();
float len = bf.GetWidthPoint(text, 12);
cb.AddTemplate(footerTemplate, document.PageSize.GetRight(180) + len, document.PageSize.GetBottom(30));
}
//Row 2
PdfPCell pdfCell4 = new PdfPCell(new Phrase("Sub Header Description", baseFontNormal));
//Row 3
PdfPCell pdfCell5 = new PdfPCell(new Phrase("Date:" + PrintTime.ToShortDateString(), baseFontBig));
PdfPCell pdfCell6 = new PdfPCell();
PdfPCell pdfCell7 = new PdfPCell(new Phrase("TIME:" + string.Format("{0:t}", DateTime.Now), baseFontBig));
//set the alignment of all three cells and set border to 0
pdfCell1.HorizontalAlignment = Element.ALIGN_CENTER;
pdfCell2.HorizontalAlignment = Element.ALIGN_CENTER;
pdfCell3.HorizontalAlignment = Element.ALIGN_CENTER;
pdfCell4.HorizontalAlignment = Element.ALIGN_CENTER;
pdfCell5.HorizontalAlignment = Element.ALIGN_CENTER;
pdfCell6.HorizontalAlignment = Element.ALIGN_CENTER;
pdfCell7.HorizontalAlignment = Element.ALIGN_CENTER;
pdfCell2.VerticalAlignment = Element.ALIGN_BOTTOM;
pdfCell3.VerticalAlignment = Element.ALIGN_MIDDLE;
pdfCell4.VerticalAlignment = Element.ALIGN_TOP;
pdfCell5.VerticalAlignment = Element.ALIGN_MIDDLE;
pdfCell6.VerticalAlignment = Element.ALIGN_MIDDLE;
pdfCell7.VerticalAlignment = Element.ALIGN_MIDDLE;
pdfCell4.Colspan = 3;
pdfCell1.Border = 0;
pdfCell2.Border = 0;
pdfCell3.Border = 0;
pdfCell4.Border = 0;
pdfCell5.Border = 0;
pdfCell6.Border = 0;
pdfCell7.Border = 0;
//add all three cells into PdfTable
pdfTab.AddCell(pdfCell1);
pdfTab.AddCell(pdfCell2);
pdfTab.AddCell(pdfCell3);
pdfTab.AddCell(pdfCell4);
pdfTab.AddCell(pdfCell5);
pdfTab.AddCell(pdfCell6);
pdfTab.AddCell(pdfCell7);
pdfTab.TotalWidth = document.PageSize.Width - 80f;
pdfTab.WidthPercentage = 70;
//pdfTab.HorizontalAlignment = Element.ALIGN_CENTER;
//call WriteSelectedRows of PdfTable. This writes rows from PdfWriter in PdfTable
//first param is start row. -1 indicates there is no end row and all the rows to be included to write
//Third and fourth param is x and y position to start writing
pdfTab.WriteSelectedRows(0, -1, 40, document.PageSize.Height - 30, writer.DirectContent);
//set pdfContent value
//Move the pointer and draw line to separate header section from rest of page
cb.MoveTo(40, document.PageSize.Height - 100);
cb.LineTo(document.PageSize.Width - 40, document.PageSize.Height - 100);
cb.Stroke();
//Move the pointer and draw line to separate footer section from rest of page
cb.MoveTo(40, document.PageSize.GetBottom(50) );
cb.LineTo(document.PageSize.Width - 40, document.PageSize.GetBottom(50));
cb.Stroke();
}
public override void OnCloseDocument(PdfWriter writer, Document document)
{
base.OnCloseDocument(writer, document);
headerTemplate.BeginText();
headerTemplate.SetFontAndSize(bf, 12);
headerTemplate.SetTextMatrix(0, 0);
headerTemplate.ShowText((writer.PageNumber - 1).ToString());
headerTemplate.EndText();
footerTemplate.BeginText();
footerTemplate.SetFontAndSize(bf, 12);
footerTemplate.SetTextMatrix(0, 0);
footerTemplate.ShowText((writer.PageNumber - 1).ToString());
footerTemplate.EndText();
}
}
I hope it helps!
We don't talk about iTextSharp anymore. You are using iText 5 for .NET. The current version is iText 7 for .NET.
Obsolete answer:
The AddHeader
has been deprecated a long time ago and has been removed from iTextSharp. Adding headers and footers is now done using page events. The examples are in Java, but you can find the C# port of the examples here and here (scroll to the bottom of the page for links to the .cs
files).
Make sure you read the documentation. A common mistake by many developers have made before you, is adding content in the OnStartPage
. You should only add content in the OnEndPage
. It's also obvious that you need to add the content at absolute coordinates (for instance using ColumnText
) and that you need to reserve sufficient space for the header and footer by defining the margins of your document correctly.
Updated answer:
If you are new to iText, you should use iText 7 and use event handlers to add headers and footers. See chapter 3 of the iText 7 Jump-Start Tutorial for .NET.
When you have a PdfDocument
in iText 7, you can add an event handler:
PdfDocument pdf = new PdfDocument(new PdfWriter(dest));
pdf.addEventHandler(PdfDocumentEvent.END_PAGE, new MyEventHandler());
This is an example of the hard way to add text at an absolute position (using PdfCanvas
):
protected internal class MyEventHandler : IEventHandler {
public virtual void HandleEvent(Event @event) {
PdfDocumentEvent docEvent = (PdfDocumentEvent)@event;
PdfDocument pdfDoc = docEvent.GetDocument();
PdfPage page = docEvent.GetPage();
int pageNumber = pdfDoc.GetPageNumber(page);
Rectangle pageSize = page.GetPageSize();
PdfCanvas pdfCanvas = new PdfCanvas(page.NewContentStreamBefore(), page.GetResources(), pdfDoc);
//Add header
pdfCanvas.BeginText()
.SetFontAndSize(C03E03_UFO.helvetica, 9)
.MoveText(pageSize.GetWidth() / 2 - 60, pageSize.GetTop() - 20)
.ShowText("THE TRUTH IS OUT THERE")
.MoveText(60, -pageSize.GetTop() + 30)
.ShowText(pageNumber.ToString())
.EndText();
pdfCanvas.release();
}
}
This is a slightly higher-level way, using Canvas
:
protected internal class MyEventHandler : IEventHandler {
public virtual void HandleEvent(Event @event) {
PdfDocumentEvent docEvent = (PdfDocumentEvent)@event;
PdfDocument pdfDoc = docEvent.GetDocument();
PdfPage page = docEvent.GetPage();
int pageNumber = pdfDoc.GetPageNumber(page);
Rectangle pageSize = page.GetPageSize();
PdfCanvas pdfCanvas = new PdfCanvas(page.NewContentStreamBefore(), page.GetResources(), pdfDoc);
//Add watermark
Canvas canvas = new Canvas(pdfCanvas, pdfDoc, page.getPageSize());
canvas.setFontColor(Color.WHITE);
canvas.setProperty(Property.FONT_SIZE, 60);
canvas.setProperty(Property.FONT, helveticaBold);
canvas.showTextAligned(new Paragraph("CONFIDENTIAL"),
298, 421, pdfDoc.getPageNumber(page),
TextAlignment.CENTER, VerticalAlignment.MIDDLE, 45);
pdfCanvas.release();
}
}
There are other ways to add content at absolute positions. They are described in the different iText books.
For iTextSharp 4.1.6, the last version of iTextSharp that was licensed as LGPL, the solution provided by Alvaro Patiño is both simple and effective.
Because documentation is somewhat scarse I'd like to extend his answer with this code snippet that can be used to change the appearance of the header and footer. By default they have a rather large font-size and a thick border, which many people will want to change.
// Parameters passed on to the function that creates the PDF
String headerText = "Your header text";
String footerText = "Page";
// Define a font and font-size in points (plus f for float) and pick a color
// This one is for both header and footer but you can also create seperate ones
Font fontHeaderFooter = FontFactory.GetFont("arial", 8f);
fontHeaderFooter.Color = Color.GRAY;
// Apply the font to the headerText and create a Phrase with the result
Chunk chkHeader = new Chunk(headerText, fontHeaderFooter);
Phrase p1 = new Phrase(chkHeader);
// create a HeaderFooter element for the header using the Phrase
// The boolean turns numbering on or off
HeaderFooter header = new HeaderFooter(p1, false);
// Remove the border that is set by default
header.Border = Rectangle.NO_BORDER;
// Align the text: 0 is left, 1 center and 2 right.
header.Alignment = 1;
// add the header to the document
document.Header = header;
// The footer is created in an similar way
// If you want to use numbering like in this example, add a whitespace to the
// text because by default there's no space in between them
if (footerText.Substring(footerText.Length - 1) != " ") footerText += " ";
Chunk chkFooter = new Chunk(footerText, fontHeaderFooter);
Phrase p2 = new Phrase(chkFooter);
// Turn on numbering by setting the boolean to true
HeaderFooter footer = new HeaderFooter(p2, true);
footer.Border = Rectangle.NO_BORDER;
footer.Alignment = 1;
document.Footer = footer;
// Open the Document for writing and continue creating its content
document.Open();
For more info check Creating PDFs with iTextSharp and iTextSharp - Adding Text with Chunks, Phrases and Paragraphs. The source code on GitHub may also be useful.
The answers to this question, while they are correct, are very unnecessarily complicated. It doesn't take that much code for text to show up in the header/footer. Here is a simple example of adding text to the header/footer.
The current version of iTextSharp works by implementing a callback class which is defined by the IPdfPageEvent
interface. From what I understand, it's not a good idea to add things during the OnStartPage
method, so instead I will be using the OnEndPage
page method. The events are triggered depending on what is happening to the PdfWriter
First, create a class which implements IPdfPageEvent
. In the:
public void OnEndPage(PdfWriter writer, Document document)
function, obtain the PdfContentByte
object by calling
PdfContentByte cb = writer.DirectContent;
Now you can add text very easily:
ColumnText ct = new ColumnText(cb);
cb.BeginText();
cb.SetFontAndSize(BaseFont.CreateFont(BaseFont.TIMES_ROMAN, BaseFont.CP1252, BaseFont.NOT_EMBEDDED), 12.0f);
//Note, (0,0) in this case is at the bottom of the document
cb.SetTextMatrix(document.LeftMargin, document.BottomMargin);
cb.ShowText(String.Format("{0} {1}", "Testing Text", "Like this"));
cb.EndText();
So the full for the OnEndPage
function will be:
public void OnEndPage(PdfWriter writer, Document document)
{
PdfContentByte cb = writer.DirectContent;
ColumnText ct = new ColumnText(cb);
cb.BeginText();
cb.SetFontAndSize(BaseFont.CreateFont(BaseFont.TIMES_ROMAN, BaseFont.CP1252, BaseFont.NOT_EMBEDDED), 12.0f);
cb.SetTextMatrix(document.LeftMargin, document.BottomMargin);
cb.ShowText(String.Format("{0} {1}", "Testing Text", "Like this"));
cb.EndText();
}
This will show up at the bottom of your document. One last thing. Don't forget to assign the IPdfPageEvent
like this:
writter.PageEvent = new PDFEvents();
To the PdfWriter
writter object
For the header it is very similar. Just flip the SetTextMatrix
y coordinate:
cb.SetTextMatrix(document.LeftMargin, document.PageSize.Height - document.TopMargin);