Add Header and Footer for Pdf Using Itextsharp

iTextSharp–Add header/footer to PDF

You are welcome "Uncle Vince" !

See this

And try this solution.

I hope I was helpful.

    MemoryStream memoryStream = new MemoryStream();
StringWriter sw = new StringWriter();
HtmlTextWriter hw = new HtmlTextWriter(sw);
pdffile.RenderControl(hw);

StringReader sr = new StringReader(sw.ToString());
string imagepath = Server.MapPath("..") + "\\Logo.jpg";
Document pdfDoc = new Document(PageSize.A4, 10f, 10f, 100f, 0f);

PdfWriter writer = PdfWriter.GetInstance(pdfDoc, memoryStream);
writer.PageEvent = new Footer();
BaseFont bfTimes = BaseFont.CreateFont(BaseFont.TIMES_ROMAN, BaseFont.CP1252, false);
iTextSharp.text.Font times = new iTextSharp.text.Font(bfTimes, 12, iTextSharp.text.Font.ITALIC, iTextSharp.text.BaseColor.MAGENTA);

pdfDoc.Open();
iTextSharp.text.Image image = iTextSharp.text.Image.GetInstance(imagepath);
pdfDoc.Add(image);

var cssResolver = new StyleAttrCSSResolver();
var cssFile = XMLWorkerHelper.GetCSS(new FileStream(HttpContext.Current.Server.MapPath("style.css"), FileMode.Open));
cssResolver.AddCss(cssFile);

//HTML
HtmlPipelineContext htmlContext = new HtmlPipelineContext(null);
htmlContext.SetTagFactory(Tags.GetHtmlTagProcessorFactory());

//Pipelines
PdfWriterPipeline pdfFile = new PdfWriterPipeline(pdfDoc, writer);
HtmlPipeline html = new HtmlPipeline(htmlContext, pdfFile);
CssResolverPipeline css = new CssResolverPipeline(cssResolver, html);

//XML Worker
XMLWorker worker = new XMLWorker(css, true);
XMLParser p = new XMLParser(worker);

p.Parse(sr);
writer.CloseStream = false;
pdfDoc.Close();
memoryStream.Close();

header and footer using itextsharp using c#

You want to assign HeaderText to objHeaderFooter in

if (!string.IsNullOrEmpty(HeaderText))
{
Header objHeaderFooter = new Header();
//Here i need to assign the string HeaderText to Header. I dont know how to do it.
}

Assuming HeaderText to be a string you can do so using the Header method setHeader:

objHeaderFooter.setHeader(new Phrase(HeaderText));

Furthermore, you have to assign objHeaderFooter to your PdfWriter instance:

pdfWriter.PageEvent = objHeaderFooter;

Thus:

if (!string.IsNullOrEmpty(HeaderText))
{
Header objHeaderFooter = new Header();
objHeaderFooter.setHeader(new Phrase(HeaderText));
pdfWriter.PageEvent = objHeaderFooter;
}

Furthermore, whenever you override a method in c#, mark it accordingly as override. In particular in your page event listener, use

public override void onEndPage(PdfWriter writer, Document document)

This is easy to forget, especially when porting java examples because in java the corresponding marker @Override is optional.


Below is the sample code provided by the op.

Response.Clear();
Response.Buffer = true;
Response.ContentType = "application/pdf";
Response.AddHeader("content-disposition", "attachment; filename=abc.pdf");
Response.Charset = "";
Response.BinaryWrite(getbinary());
Response.End();

public byte[] getbinary()
{
Document pdfReport = null;
pdfReport = new Document(PageSize.A4, 25, 25, 40, 25);
MemoryStream msReport = new MemoryStream();
PdfWriter pdfWriter = PdfWriter.GetInstance(pdfReport, msReport);

pdfReport.Open();

if (!string.IsNullOrEmpty("Header Text"))
{
Header objHeaderFooter = new Header();
objHeaderFooter.SetHeader(new Phrase("Header Text"));
pdfWriter.PageEvent = objHeaderFooter;
}

PdfPTable ptData1 = new PdfPTable(1);
ptData1.SpacingBefore = 8;
ptData1.DefaultCell.Padding = 1;
ptData1.WidthPercentage = 100;
ptData1.DefaultCell.HorizontalAlignment = Element.ALIGN_CENTER;
ptData1.DefaultCell.VerticalAlignment = Element.ALIGN_MIDDLE;

PdfPCell cell1 = new PdfPCell();
cell1.BorderWidth = 0.001F;
cell1.BackgroundColor = new BaseColor(250, 250, 250);
cell1.BorderColor = new BaseColor(100, 100, 100);
cell1.Phrase = new Phrase("Sample text");
ptData1.AddCell(cell1);


PdfPCell cell = new PdfPCell();
cell.BorderWidth = 0.001F;
cell.BackgroundColor = new BaseColor(200, 200, 200);
cell.BorderColor = new BaseColor(100, 100, 100);

cell.Phrase = new Phrase("test value");
ptData1.AddCell(cell);
pdfReport.Add(ptData1);

pdfReport.Close();
return msReport.ToArray();

}

public class Header : PdfPageEventHelper
{
protected Phrase header;

public void SetHeader(Phrase header)
{
this.header = header;
}

public void onEndPage(PdfWriter writer, Document document)
{
PdfContentByte canvas = writer.DirectContent;
ColumnText.ShowTextAligned(canvas, Element.ALIGN_RIGHT, header, 559, 806, 0);
}
}

Adding Header to PDF Files using itextsharp (c#) - just new chapter pages

Add an extra parameter to your HeaderPageEvent:

class HeaderPageEvent : PdfPageEventHelper
{
boolean ignoreHeader = true;
float marginHorizontal = 42.6f;
float marginTop = 777;
// rest of your code...
}

Use this extra parameter like this:

public override void OnEndPage(PdfWriter writer, Document document)
{
if (ignoreHeader) return;
ignoreHeader = true;
// rest of your code...
}

By doing so, you tell the event only to show the header if the value of ignoreHeader is false and if it's false, it's set to true immediately.

By default, the header will never be shown, which is what you want. You only want to show the header when you want it. You can accomplish this by adding this method to your HeaderPageEvent:

void ShowHeader() {
ignoreHeader = false;
}

You no longer need to set the page event to null. You can now just trigger the showHeader() method every time you want a header to turn up.

HeaderPageEvent event = new HeaderPageEvent();
writer.PageEvent = event;
// Add stuff, no header will be added
event.ShowHeader();
document.NewPage();
// A header will be shown, but only on one page
document.Add(table);

If you want the header to appear on the first page, you need to change the default value of ignoreHeader to false.

Footer in pdf with iTextSharp

I manage to fix doing this.
In my class that create the pdf i add this line.

pdfWriter.PageEvent = new PDFFooter();

and i created another class called PDFFooter.

 public class PDFFooter : PdfPageEventHelper
{
// write on top of document
public override void OnOpenDocument(PdfWriter writer, Document document)
{
base.OnOpenDocument(writer, document);
PdfPTable tabFot = new PdfPTable(new float[] { 1F });
tabFot.SpacingAfter = 10F;
PdfPCell cell;
tabFot.TotalWidth = 300F;
cell = new PdfPCell(new Phrase(""));
cell.Border = Rectangle.NO_BORDER;
tabFot.AddCell(cell);
tabFot.WriteSelectedRows(0, -1, 150, document.Top, writer.DirectContent);
}

// write on start of each page
public override void OnStartPage(PdfWriter writer, Document document)
{
base.OnStartPage(writer, document);
}

// write on end of each page
public override void OnEndPage(PdfWriter writer, Document document)
{
DateTime horario = DateTime.Now;
base.OnEndPage(writer, document);
PdfPTable tabFot = new PdfPTable(new float[] { 1F });
PdfPCell cell;
tabFot.TotalWidth = 300F;
cell = new PdfPCell(new Phrase("TEST"+" - " + horario));
cell.Border = Rectangle.NO_BORDER;
cell.HorizontalAlignment = Element.ALIGN_CENTER;
tabFot.AddCell(cell);
tabFot.WriteSelectedRows(0, -1, 150, document.Bottom, writer.DirectContent);
}

//write on close of document
public override void OnCloseDocument(PdfWriter writer, Document document)
{
base.OnCloseDocument(writer, document);
}
}
}

Header and Footer in ITextSharp

You are creating your Document like this:

Document doc = new Document(iTextSharp.text.PageSize.LEDGER, 10, 10, 42, 35);

This means that you have a top margin of 42 user units and a bottom margin of 35 user units. You can use this margin to add extra content in a page event.

The official web site has plenty of examples and a comprehensive Q&A section. All examples and answers are tagged. If you click on the header tag, you can find plenty of examples.

As already indicated by others in the comments, you need to create a PdfPageEvent implementation. The easiest way to do this, is by extending the PdfPageEventHelper class.

class MyHeaderFooterEvent : PdfPageEventHelper {
Font FONT = new Font(Font.FontFamily.HELVETICA, 18, Font.BOLD);

public override void OnEndPage(PdfWriter writer, Document document) {
PdfContentByte canvas = writer.DirectContent;
ColumnText.ShowTextAligned(
canvas, Element.ALIGN_LEFT,
new Phrase("Header", FONT), 10, 810, 0
);
ColumnText.ShowTextAligned(
canvas, Element.ALIGN_LEFT,
new Phrase("Footer", FONT), 10, 10, 0
);
}
}

Important to know:

  • It is forbidden to add content in the OnStartPage() event. Add your header and footer when all the content has been added to the page just before iTextSharp moves to a new page. More specifically: add content in the OnEndPage() event.
  • It is forbidden to add content to the Document object that is passed to the event. This object can be used for read-only purposes only.

If you examine the OnEndPage() method in the MyHeaderFooterEvent class, you see that we get the DirectContent from the writer and that we add content to this canvas using ShowTextAligned methods. There are many other ways to add content, but you explicitly asked for the easiest way. This way has its limitations, but it's easy.

I used a couple of hard-coded values: I used 10 as the x value for the header and the footer. That's because you defined a left margin of 10 user units. The header and footer are left aligned with the actual content you're adding to the page. I used 810 for the y value of the header because you're creating an A4 page with a top margin of 42. The top y coordinate of your page is 842. The top y coordinate of the top margin is 842 - 42 = 800. I added 10 user units so that your header isn't glued to the actual content. The bottom y coordinate of the page is 0 in your case and the bottom y coordinate of the margin in 35. I used 10 for the base line of the footer.

You created wri and right after creating this PdfWriter instance, you open the Document instance. For the page event to take effect, you should add the following link, right before opening the Document:

wri.PageEvent = new MyHeaderFooterEvent();

Now the OnEndPage() method will be invoked every time your main process finalizes a page.

Important: you added //Code to add header/footer at the wrong place. iTextSharp will try to flush the content of a page as soon as possible. If you add code to add a header/footer after you've added content, you can not go back to add a header and footer to pages that were already flushed to the output stream.

ItextSharp : How to set dynamic header using ITextsharp. C#.Net

Although it looks like you're on the right track, must be a bad copy/paste for your ReportPdfHeaderFooter class above, which won't compile as-is.

Here's a simple working example to get you started.

First the PdfPageEventHelper implementation:

public class PageEventHeader : PdfPageEventHelper
{
public string HeaderText { get; set; }

public override void OnEndPage(PdfWriter writer, Document document)
{
float cellHeight = document.TopMargin;
Rectangle page = document.PageSize;
PdfPTable table = new PdfPTable(1) { TotalWidth = page.Width };
table.AddCell(new PdfPCell(new Phrase(HeaderText))
{
Border = PdfPCell.NO_BORDER,
FixedHeight = cellHeight,
HorizontalAlignment = Element.ALIGN_CENTER
});
table.WriteSelectedRows(
0, -1, 0,
page.Height - cellHeight + table.TotalHeight,
writer.DirectContent
);
}
}

Second, the test PDF file creation:

using (var stream = new MemoryStream())
{
var header = new PageEventHeader();
using (Document document = new Document())
{
var writer = PdfWriter.GetInstance(document, stream);
document.Open();

writer.PageEvent = header;
header.HeaderText = "Header 0";
document.Add(new Phrase("Header 0"));
document.NewPage();
header.HeaderText = "Header 1";
document.Add(new Phrase("Header 1"));
}
File.WriteAllBytes(OUTPUT_FILE, stream.ToArray());
}

How to add Header and Footer to a PDF with iText 7

The iText 7 .Net sample TextFooter.cs illustrates how to automatically add headers and footers by means of events:

public class TextFooter
{
public static readonly String DEST = "results/sandbox/events/text_footer.pdf";

public static void Main(String[] args)
{
FileInfo file = new FileInfo(DEST);
file.Directory.Create();

new TextFooter().ManipulatePdf(DEST);
}

protected void ManipulatePdf(String dest)
{
PdfDocument pdfDoc = new PdfDocument(new PdfWriter(dest));
Document doc = new Document(pdfDoc);
pdfDoc.AddEventHandler(PdfDocumentEvent.END_PAGE, new TextFooterEventHandler(doc));

for (int i = 0; i < 3; i++)
{
doc.Add(new Paragraph("Test " + (i + 1)));
if (i != 2)
{
doc.Add(new AreaBreak());
}
}

doc.Close();
}

private class TextFooterEventHandler : IEventHandler
{
protected Document doc;

public TextFooterEventHandler(Document doc)
{
this.doc = doc;
}

public void HandleEvent(Event currentEvent)
{
PdfDocumentEvent docEvent = (PdfDocumentEvent) currentEvent;
Rectangle pageSize = docEvent.GetPage().GetPageSize();
PdfFont font = null;
try {
font = PdfFontFactory.CreateFont(StandardFonts.HELVETICA_OBLIQUE);
}
catch (IOException e)
{
Console.Error.WriteLine(e.Message);
}

float coordX = ((pageSize.GetLeft() + doc.GetLeftMargin())
+ (pageSize.GetRight() - doc.GetRightMargin())) / 2;
float headerY = pageSize.GetTop() - doc.GetTopMargin() + 10;
float footerY = doc.GetBottomMargin();
Canvas canvas = new Canvas(docEvent.GetPage(), pageSize);
canvas
.SetFont(font)
.SetFontSize(5)
.ShowTextAligned("this is a header", coordX, headerY, TextAlignment.CENTER)
.ShowTextAligned("this is a footer", coordX, footerY, TextAlignment.CENTER)
.Close();
}
}
}


Related Topics



Leave a reply



Submit