Get total number of pages in iTextsharp PDF C# - c#

I am using iTextSharp for pdf generating purpose . I want to get page no with total page show on footer.
my code is-
public class footer : PdfPageEventHelper
{
public override void OnEndPage(PdfWriter writer, Document doc)
{
PdfPTable footerTbl = new PdfPTable(1);
footerTbl.TotalWidth = doc.PageSize.Width;
Chunk myFooter = new Chunk("Page " + (doc.PageNumber) + " of " + doc.PageCount, FontFactory.GetFont(FontFactory.HELVETICA_OBLIQUE, 8, grey))
PdfPCell footer = new PdfPCell(new Phrase(myFooter));
footer.Border = Rectangle.NO_BORDER;
footer.HorizontalAlignment = Element.ALIGN_RIGHT;
footerTbl.AddCell(footer);
footerTbl.WriteSelectedRows(0, -1, 0, (doc.BottomMargin + 10), writer.DirectContent);
}
doc.PageCount is give an error

you need to extent ITextEvents class that extends PdfPageEventHelper to add footer. in following way.
public class footer : PdfPageEventHelper
{
// This is the contentbyte object of the writer
PdfContentByte cb;
// we will put the final number of pages in a template
PdfTemplate footerTemplate;
// this is the BaseFont we are going to use for the header / footer
BaseFont bf = null;
public override void OnOpenDocument(PdfWriter writer, Document document)
{
try
{
bf = BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.NOT_EMBEDDED);
cb = writer.DirectContent;
footerTemplate = cb.CreateTemplate(50, 50);
}
catch (DocumentException de)
{
//handle exception here
}
catch (System.IO.IOException ioe)
{
//handle exception here
}
}
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 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));
}
pdfTab.TotalWidth = document.PageSize.Width - 80f;
pdfTab.WidthPercentage = 70;
}
public override void OnCloseDocument(PdfWriter writer, Document document)
{
base.OnCloseDocument(writer, document);
footerTemplate.BeginText();
footerTemplate.SetFontAndSize(bf, 12);
footerTemplate.SetTextMatrix(0, 0);
footerTemplate.ShowText((writer.PageNumber - 1).ToString());
footerTemplate.EndText();
}
}

Related

how to add footer (with variables/class) with itextsharp pdf

I have this code and I want to add a table as a footer. But the problem is I cannot pass the variables:
Document doc = new Document();
doc.AddTitle("e-8D Report_" + report.OSIE8DNO + ".pdf");
PdfWriter writer = PdfWriter.GetInstance(doc, fs);
doc.SetPageSize(PageSize.A4);
doc.SetMargins(18f, 18f, 18f, 18f); // 0.25 inch margins
doc.Open();
PdfPTable table = new PdfPTable(10)
{
WidthPercentage = 100,
LockedWidth = true,
TotalWidth = 560f
};
float[] widths = new float[] { 32f, 73f, 70f, 70f, 70f, 70f, 70f, 70f, 73f, 32f };
table.SetWidths(widths);
// rest of the document
// ...
// rest of the document
// Below is the part that I want to add as footer
#region Footer
// left margin
cell = new PdfPCell(new Phrase(" ", font6))
{
Border = Rectangle.NO_BORDER
};
table.AddCell(cell);
cell = new PdfPCell(new Phrase("Reviewed & Approved by :", font6))
{
Colspan = 4,
BackgroundColor = bgBlue,
HorizontalAlignment = Element.ALIGN_LEFT,
Border = Rectangle.TOP_BORDER | Rectangle.LEFT_BORDER
};
table.AddCell(cell);
cell = new PdfPCell(new Phrase("For document approval by email, no Manual / e-Signature required &", font2))
{
Colspan = 4,
BackgroundColor = bgBlue,
HorizontalAlignment = Element.ALIGN_LEFT,
Border = Rectangle.TOP_BORDER | Rectangle.RIGHT_BORDER
};
table.AddCell(cell);
// right margin
cell = new PdfPCell(new Phrase(" ", font6))
{
Border = Rectangle.NO_BORDER
};
table.AddCell(cell);
// the rest of the cell
//...
// the rest of the cell
#endregion
doc.Add(table);
//writer.PageEvent = new PDFFooter();
doc.Close();
With this variables, I can't make the footer with PdfPageEventHelper from this source:
Footer in pdf with iTextSharp
Please help
Already got the answer. I add parameter to the PdfPageEventHelper Class:
public PdfPTable footer { get; set; }
public override void OnEndPage(PdfWriter writer, Document document)
{
base.OnEndPage(writer, document);
document.Add(footer);
}
And call from the page (create complete table first on the page):
writer.PageEvent = new PDFHeaderFooter() { footer = table };

iTextSharp set dynamic margins

I need help with an issue I've been experiencing with iTextSharp.
I want to set the margins dynamically depending on wether the page has a header/footer or not, without having to always set it up manually for each page. As it does that, though it always seems to do it on the page after the one I want. I reckon it must be a question of putting my code before something. I'm thinking that when the OnStartPage method gets called the NewPage method of the Document class has already been called. Is that it? That's the only plausible explaination that makes sense to me.
I could do this on the class that creates the pdf file. Call the method everytime before calling the NewPage method. But I want something more automated.
So, here are the methods that will create the actual pdf file:
using iTextSharp.text;
using iTextSharp.text.pdf;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace WebApplication4.Models
{
public class ITextEvents : PdfPageEventHelper
{
Font FontRegular = new Font(Font.FontFamily.HELVETICA, 12);
// 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;
List<int> PagesWithNoFooter, PagesWithNoHeader;
float LeftMargin, RightMargin, TopMarginWithHeader, TopMarginWithNoHeader, BottomMarginWithFooter, BottomMarginWithNoFooter;
/// <summary>
/// The constructor for getting some presets
/// </summary>
/// <param name="pagesWithNoHeader">List of pages in which the user doesn't want a header.</param>
/// <param name="pagesWithNoFooter">List of pages in which the user doesn't want a footer.</param>
/// <param name="leftMargin">The page's default left margin.</param>
/// <param name="rightMargin">The page's default right margin.</param>
/// <param name="topMarginWithNoHeader">The page's top margin for a page with no header.</param>
/// <param name="topMarginWithHeader">The page's top margin for a page with header.</param>
/// <param name="bottomMarginWithNoFooter">The page's bottom margin for a page with no footer.</param>
/// <param name="bottomMarginWithFooter">The page's bottom margin for a page with footer.</param>
public ITextEvents(List<int> pagesWithNoHeader, List<int> pagesWithNoFooter, float leftMargin, float rightMargin, float topMarginWithNoHeader, float topMarginWithHeader, float bottomMarginWithNoFooter, float bottomMarginWithFooter)
{
PagesWithNoFooter = pagesWithNoFooter.OrderBy(i => i).ToList();
PagesWithNoHeader = pagesWithNoHeader.OrderBy(i => i).ToList();
LeftMargin = leftMargin;
RightMargin = rightMargin;
TopMarginWithHeader = topMarginWithHeader;
TopMarginWithNoHeader = topMarginWithNoHeader;
BottomMarginWithFooter = bottomMarginWithFooter;
BottomMarginWithNoFooter = bottomMarginWithNoFooter;
}
public override void OnOpenDocument(PdfWriter writer, Document document)
{
try
{
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)
{
//handle exception here
}
catch (System.IO.IOException ioe)
{
//handle exception here
}
}
public override void OnStartPage(PdfWriter writer, Document document)
{
base.OnStartPage(writer, document);
float[] docMargins = SetDocumentMargins(writer.CurrentPageNumber);
document.SetMargins(docMargins[0], docMargins[1], docMargins[2], docMargins[3]);
}
public override void OnEndPage(PdfWriter writer, Document document)
{
base.OnEndPage(writer, document);
// Adds the footer if the user didn't specify the page number
if (!PagesWithNoFooter.Contains(document.PageNumber))
{
//Add paging to footer
{
string paging = "Página " + writer.PageNumber + " de ";
float len = bf.GetWidthPoint(paging, 12);
float posX = (document.PageSize.Width / 2) - (len / 2);
cb.BeginText();
cb.SetFontAndSize(bf, 12);
cb.SetTextMatrix(posX, document.PageSize.GetBottom(30));
cb.ShowText(paging);
cb.EndText();
cb.AddTemplate(footerTemplate, posX + len, document.PageSize.GetBottom(30));
}
}
// Adds the header if the user didn't specify the page number
if (!PagesWithNoHeader.Contains(document.PageNumber))
{
Phrase p1Header = new Phrase("Sample Header Here", FontRegular);
//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 ";
//Row 2
PdfPCell pdfCell4 = new PdfPCell(new Phrase("Sub Header Description", FontRegular));
//Row 3
PdfPCell pdfCell5 = new PdfPCell(new Phrase("Date:", FontRegular));
PdfPCell pdfCell6 = new PdfPCell();
PdfPCell pdfCell7 = new PdfPCell(new Phrase("TIME:" + string.Format("{0:t}", DateTime.Now), FontRegular));
//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;
//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);
//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();
}
}
public override void OnCloseDocument(PdfWriter writer, Document document)
{
base.OnCloseDocument(writer, document);
footerTemplate.BeginText();
footerTemplate.SetFontAndSize(bf, 12);
footerTemplate.SetTextMatrix(0, 0);
footerTemplate.ShowText(writer.PageNumber.ToString());
footerTemplate.EndText();
}
private float[] SetDocumentMargins(int pageNumber)
{
float topMargin = 0, bottomMargin = 0;
// Sets the bottom margin depending on wether the page has a footer
if (PagesWithNoFooter.Contains(pageNumber))
bottomMargin = BottomMarginWithNoFooter;
else
bottomMargin = BottomMarginWithFooter;
// Sets the top margin depending on wether the page has a header
if (PagesWithNoHeader.Contains(pageNumber))
topMargin = TopMarginWithNoHeader;
else
topMargin = TopMarginWithHeader;
return new float[] { LeftMargin, RightMargin, topMargin, bottomMargin };
}
}
}
And here's the code for the PdfPageEventHelper:
using iTextSharp.text;
using iTextSharp.text.pdf;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace WebApplication4.Models
{
public class ITextEvents : PdfPageEventHelper
{
Font FontRegular = new Font(Font.FontFamily.HELVETICA, 12);
// 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;
List<int> PagesWithNoFooter, PagesWithNoHeader;
float LeftMargin, RightMargin, TopMarginWithHeader, TopMarginWithNoHeader, BottomMarginWithFooter, BottomMarginWithNoFooter;
/// <summary>
/// The constructor for getting some presets
/// </summary>
/// <param name="pagesWithNoHeader">List of pages in which the user doesn't want a header.</param>
/// <param name="pagesWithNoFooter">List of pages in which the user doesn't want a footer.</param>
/// <param name="leftMargin">The page's default left margin.</param>
/// <param name="rightMargin">The page's default right margin.</param>
/// <param name="topMarginWithNoHeader">The page's top margin for a page with no header.</param>
/// <param name="topMarginWithHeader">The page's top margin for a page with header.</param>
/// <param name="bottomMarginWithNoFooter">The page's bottom margin for a page with no footer.</param>
/// <param name="bottomMarginWithFooter">The page's bottom margin for a page with footer.</param>
public ITextEvents(List<int> pagesWithNoHeader, List<int> pagesWithNoFooter, float leftMargin, float rightMargin, float topMarginWithNoHeader, float topMarginWithHeader, float bottomMarginWithNoFooter, float bottomMarginWithFooter)
{
PagesWithNoFooter = pagesWithNoFooter.OrderBy(i => i).ToList();
PagesWithNoHeader = pagesWithNoHeader.OrderBy(i => i).ToList();
LeftMargin = leftMargin;
RightMargin = rightMargin;
TopMarginWithHeader = topMarginWithHeader;
TopMarginWithNoHeader = topMarginWithNoHeader;
BottomMarginWithFooter = bottomMarginWithFooter;
BottomMarginWithNoFooter = bottomMarginWithNoFooter;
}
public override void OnOpenDocument(PdfWriter writer, Document document)
{
try
{
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)
{
//handle exception here
}
catch (System.IO.IOException ioe)
{
//handle exception here
}
}
public override void OnStartPage(PdfWriter writer, Document document)
{
base.OnStartPage(writer, document);
float[] docMargins = SetDocumentMargins(writer.CurrentPageNumber);
document.SetMargins(docMargins[0], docMargins[1], docMargins[2], docMargins[3]);
}
public override void OnEndPage(PdfWriter writer, Document document)
{
base.OnEndPage(writer, document);
// Adds the footer if the user didn't specify the page number
if (!PagesWithNoFooter.Contains(document.PageNumber))
{
//Add paging to footer
{
string paging = "Página " + writer.PageNumber + " de ";
float len = bf.GetWidthPoint(paging, 12);
float posX = (document.PageSize.Width / 2) - (len / 2);
cb.BeginText();
cb.SetFontAndSize(bf, 12);
cb.SetTextMatrix(posX, document.PageSize.GetBottom(30));
cb.ShowText(paging);
cb.EndText();
cb.AddTemplate(footerTemplate, posX + len, document.PageSize.GetBottom(30));
}
}
// Adds the header if the user didn't specify the page number
if (!PagesWithNoHeader.Contains(document.PageNumber))
{
Phrase p1Header = new Phrase("Sample Header Here", FontRegular);
//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 ";
//Row 2
PdfPCell pdfCell4 = new PdfPCell(new Phrase("Sub Header Description", FontRegular));
//Row 3
PdfPCell pdfCell5 = new PdfPCell(new Phrase("Date:", FontRegular));
PdfPCell pdfCell6 = new PdfPCell();
PdfPCell pdfCell7 = new PdfPCell(new Phrase("TIME:" + string.Format("{0:t}", DateTime.Now), FontRegular));
//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;
//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);
//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();
}
}
public override void OnCloseDocument(PdfWriter writer, Document document)
{
base.OnCloseDocument(writer, document);
footerTemplate.BeginText();
footerTemplate.SetFontAndSize(bf, 12);
footerTemplate.SetTextMatrix(0, 0);
footerTemplate.ShowText(writer.PageNumber.ToString());
footerTemplate.EndText();
}
private float[] SetDocumentMargins(int pageNumber)
{
float topMargin = 0, bottomMargin = 0;
// Sets the bottom margin depending on wether the page has a footer
if (PagesWithNoFooter.Contains(pageNumber))
bottomMargin = BottomMarginWithNoFooter;
else
bottomMargin = BottomMarginWithFooter;
// Sets the top margin depending on wether the page has a header
if (PagesWithNoHeader.Contains(pageNumber))
topMargin = TopMarginWithNoHeader;
else
topMargin = TopMarginWithHeader;
return new float[] { LeftMargin, RightMargin, topMargin, bottomMargin };
}
}
}

Header and Footer for each PDF page

I'm trying to generate a PDF file using iTextSharp, so I managed to generate my PDF files as below:
This is my Code :
In my controller I get data from String (JSON format) <---- String screendata:
[HttpPost]
public void GenaraleExportPDF(String screendata,String monTitre,String file)
{
ExportManager export = new ExportManager();
String MapPath = Server.MapPath("~/Content/");
string filepath = MapPath + file;
//Appel Methodes Export Manager pour generer PDF
export.GenererPdfJSON(screendata, monTitre, MapPath, file);
//Ajout Response : transmitfile self buffers
Response.Buffer = false;
Response.Clear();
Response.ClearContent();
Response.ClearHeaders();
Response.ContentType = "application/pdf";
Response.AddHeader("Content-Disposition", "attachment; filename=" + file);
Response.TransmitFile(filepath);
Response.End();
}
Others functions :
Generate Header and Data of table --> AjoutHeaderDataTablePdf() :
public PdfPTable AjoutHeaderDataTablePdf(object[] tableObjet, PdfPTable table, iTextSharp.text.Font fntTableFontHdr)
{
table.HeaderRows = 2;
table.HorizontalAlignment = 0;
table.TotalWidth = 500f;
table.LockedWidth = true;
float[] widths = new float[] { 60f, 40f, 60f, 40f, 60f, 80f};
table.SetWidths(widths);
//Font Color
BaseColor ForeGroundmyColorHeader = WebColors.GetRGBColor("#FFFFFF");
BaseColor ForeGroundmyColorOthers = WebColors.GetRGBColor("#232323");
BaseColor BackGroundmyColor = WebColors.GetRGBColor("#32A3E0");
BaseColor BackGroundmyColorOther1 = WebColors.GetRGBColor("#D8E4FD");
BaseColor BackGroundmyColorOther2 = WebColors.GetRGBColor("#FFFFFF");
var FontHeader = FontFactory.GetFont("Times New Roman", 9, ForeGroundmyColorHeader);
var FontOthers = FontFactory.GetFont("Times New Roman", 8, ForeGroundmyColorOthers);
var borderColor = WebColors.GetRGBColor("#E4E4E4");
var borderWidth =0f;
/***Begin Header***/
/******Fin Header******/
// Ajout Headers columnsName
foreach (var o in tableObjet)
{
Dictionary<string, object> dictionary = (Dictionary<string, object>)o;
foreach (KeyValuePair<string, object> pair in dictionary)
{
PdfPCell CellOneHdr2 = new PdfPCell(new Phrase(pair.Key, FontHeader));
CellOneHdr2.BackgroundColor = BackGroundmyColor;
CellOneHdr2.BorderColorLeft = borderColor;
CellOneHdr2.BorderColorRight = borderColor;
CellOneHdr2.BorderColorTop = borderColor;
CellOneHdr2.BorderColorBottom = borderColor;
CellOneHdr2.BorderWidthLeft = borderWidth;
CellOneHdr2.BorderWidthRight = borderWidth;
CellOneHdr2.BorderWidthTop = borderWidth;
CellOneHdr2.BorderWidthBottom = borderWidth;
CellOneHdr2.PaddingTop = 6f;
CellOneHdr2.PaddingLeft = 5f;
CellOneHdr2.FixedHeight = 26f;
table.AddCell(CellOneHdr2);
}
break;
}
//Ajout de contenu de cellules
int count = 0;
BaseColor BackGroundmyColorOtherX;
for (int ii = 0; ii < 5; ii++)
{
foreach (var o in tableObjet)
{
Dictionary<string, object> dictionary = (Dictionary<string, object>)o;
if (count % 2 == 0)
BackGroundmyColorOtherX = BackGroundmyColorOther1;
else
BackGroundmyColorOtherX = BackGroundmyColorOther2;
foreach (KeyValuePair<string, object> pair in dictionary)
{
PdfPCell CellOneHdr2 = new PdfPCell(new Phrase(pair.Value.ToString(), FontOthers));
CellOneHdr2.BackgroundColor = BackGroundmyColorOtherX;
CellOneHdr2.FixedHeight = 23f;
CellOneHdr2.BorderColorLeft = borderColor;
CellOneHdr2.BorderColorRight = borderColor;
CellOneHdr2.BorderColorTop = borderColor;
CellOneHdr2.BorderColorBottom = borderColor;
CellOneHdr2.BorderWidthLeft = borderWidth;
CellOneHdr2.BorderWidthRight = borderWidth;
CellOneHdr2.BorderWidthTop = borderWidth;
CellOneHdr2.BorderWidthBottom = borderWidth;
CellOneHdr2.PaddingTop = 6f;
CellOneHdr2.PaddingLeft = 5f;
table.AddCell(CellOneHdr2);
}
count++;
}
}
table.HorizontalAlignment = 1;
return table;
}
Generate title of table --> TitreTablePdfCentre() :
public PdfPTable TitreTablePdfCentre(int NbrCol, String Titre)
{
BaseColor ForeGroundmyColorHeader = WebColors.GetRGBColor("#FFFFFF");
BaseColor BackGroundmyColorHeader = WebColors.GetRGBColor("#32A3E0");
var borderColor = WebColors.GetRGBColor("#E4E4E4");
var borderWidth = 0.1f;
var FontHeader = FontFactory.GetFont("Times New Roman", 12, ForeGroundmyColorHeader);
//Creer PdfTable contenant NbrCol colonnes
PdfPTable table = new PdfPTable(NbrCol);
table.HeaderRows = 2;
//Ajouter un Titre en haut du fichier
PdfPCell cell = new PdfPCell(new Phrase(Titre, FontHeader));
// fusionner les NbrCol celllules en une seul cellule
cell.Colspan = NbrCol;
//Metre au centre : 0=Left, 1=Centre, 2=Right
cell.HorizontalAlignment = 1;
// Ajout La cellule à Pdftable
/**Style**/
cell.FixedHeight = 30f;
cell.PaddingTop = 6f;
cell.BackgroundColor = BackGroundmyColorHeader;
cell.BorderColorLeft = borderColor;
cell.BorderColorRight = borderColor;
cell.BorderColorTop = borderColor;
cell.BorderColorBottom = borderColor;
cell.BorderWidthLeft = borderWidth;
cell.BorderWidthRight = borderWidth;
cell.BorderWidthTop = borderWidth;
cell.BorderWidthBottom = borderWidth;
table.AddCell(cell);
table.HorizontalAlignment = 1;
return table;
}
Generate Data From Json --> GenererPdfJSON() :
public void GenererPdfJSON(String screendata, String Titre, String MapPath, String file)
{
//Convertir String JSON to Table object[]
object[] tableObjet = TbaleJSON(screendata);
//Retourne Nbr Lignes Object
int nbrlignes = NbrLignesTableJSON(tableObjet);
//Calcul de nombre de colonnes de tableObjet
int nbrcol = NbrColonnesTableJSON(tableObjet);
//Creer PdfTable contenant nbrcol colonnes en heut de la feuille
PdfPTable table = TitreTablePdfCentre(nbrcol, Titre);
table.HeaderRows = 2;
Document document = new Document();
//Ajout de qlq Style
iTextSharp.text.Font fntTableFontHdr = FontFactory.GetFont("Arial", 8, iTextSharp.text.Font.BOLD, BaseColor.BLACK);
//Lien Physique Server.MapPath("~/Content/") + fichierpdf.pdf
string filepath = MapPath + file;
//Ecrire les données dans le fichier
PdfWriter writer = PdfWriter.GetInstance(document, new FileStream(filepath, FileMode.Create));
//Ouvrir le document
document.Open();
/**pagination***/
Paragraph para = new Paragraph("Hello world. Checking Header Footer", new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.HELVETICA, 22));
para.Alignment = Element.ALIGN_CENTER;
document.Add(para);
//*****************//
//Ajouter le noms colonnes et les donnees dans les cellules avec Style fntTableFontHdr
table = AjoutHeaderDataTablePdf(tableObjet, table, fntTableFontHdr);
document.Add(table);
document.Close();
}
My issue is that I want to create Header and Footer for each page to show page number, title, ...
Footers and headers can be added by overriding PdfPageEventHelper. The following code needs to be associated the with the current document by adding an instance of your class to the PdfWriters Page Event e.g. writer.PageEvent = new PageEventHelper();. As a side point this must be placed before the document is opened.
The OnEndPage is called when document.NewPage() is called and adds the current page number at the specified location. To also add the "of Y" we need to wait until the document is closed to ensure we get the correct number of pages.
public class PageEventHelper : PdfPageEventHelper
{
PdfContentByte cb;
PdfTemplate template;
public override void OnOpenDocument(PdfWriter writer, Document document)
{
cb = writer.DirectContent;
template = cb.CreateTemplate(width, height);
}
public override void OnEndPage(PdfWriter writer, Document document)
{
base.OnEndPage(writer, document);
int pageN = writer.PageNumber;
String text = "Page " + pageN.ToString() + " of ";
Rectangle pageSize = document.PageSize;
cb.BeginText();
cb.SetFontAndSize(BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.NOT_EMBEDDED), 12F);
cb.SetTextMatrix(Width, Height);
cb.ShowText(text);
cb.EndText();
//Add the template to each page so we can add the total page number later
cb.AddTemplate(template, Width, Height);
}
public override void OnCloseDocument(PdfWriter writer, Document document)
{
base.OnCloseDocument(writer, document);
template.SetFontAndSize(BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.NOT_EMBEDDED), 12F);
template.BeginText();
template.SetTextMatrix(0, 0);
//Add the final page number.
template.ShowText("" + (writer.PageNumber - 1));
//This will write the number on all templates on all pages
template.EndText();
}
}
More details on the PdfPageEvenHelper class can be found at http://api.itextpdf.com/itext/com/itextpdf/text/pdf/PdfPageEventHelper.html. This is written in Java but quite easy to use the same code in c#.
This principle can be used to add both footers and headers by using different templates.

iTextsharp landscape document

I am trying to create Landscape PDF using iTextSharp but It is still showing portrait. I am using following code with rotate:
Document document = new Document(PageSize.A4, 0, 0, 150, 20);
FileStream msReport = new FileStream(Server.MapPath("~/PDFS/") + "Sample1.pdf", FileMode.Create);
try
{
// creation of the different writers
PdfWriter writer = PdfWriter.GetInstance(document, msReport);
document.Open();
PdfPTable PdfTable = new PdfPTable(1);
PdfTable.SpacingBefore = 30f;
PdfPCell PdfPCell = null;
Font fontCategoryheader = new Font(Font.HELVETICA, 10f, Font.BOLD, Color.BLACK);
for (int i = 0; i < 20; i++)
{
PdfPCell = new PdfPCell(new Phrase(new Chunk("Sales Manager: ", fontCategoryheader)));
PdfPCell.BorderWidth = 0;
PdfPCell.HorizontalAlignment = Element.ALIGN_LEFT;
if (i % 2 == 0)
PdfPCell.BackgroundColor = Color.LIGHT_GRAY;
PdfPCell.PaddingBottom = 5f;
PdfPCell.PaddingLeft = 2f;
PdfPCell.PaddingTop = 4f;
PdfPCell.PaddingRight = 4f;
PdfTable.AddCell(PdfPCell);
}
document.Add(PdfTable);
document.NewPage();
}
catch (Exception ex)
{
Console.Error.WriteLine(ex.Message);
}
finally
{
// we close the document
document.Close();
}
Please suggest solution.
Thanks.
Try this
Document Doc = new Document(new Rectangle(288f, 144f), 10, 10, 10, 10);
Doc.SetPageSize(iTextSharp.text.PageSize.A4.Rotate());
you might also need this to expand a table to max width.
var _pdf_table = new PdfPTable(2); // table with two columns
PdfPCell hc = new PdfPCell();
_pdf_table.WidthPercentage = 100; //table width to 100per
_pdf_table.SetTotalWidth(new float[] { 25, iTextSharp.text.PageSize.A4.Rotate().Width - 25 });// width of each column
You must make sure that when setting the page size you do it before a call to Doc.Open();
Regards.
No need to initialize the Document and reset the page size...
Document doc = new Document(iTextSharp.text.PageSize.A4.Rotate(), 10, 10, 10, 10);
...will do the trick.
(4.1.6.0)

iTextSharp PageNumber but not on first and last pages

I am trying to show the page number of my PDF pages, but I don`t want to show it on first and last pages, because they are covers.
I use this code:
public class PDFPage : iTextSharp.text.pdf.PdfPageEventHelper
{
//I create a font object to use within my footer
protected iTextSharp.text.Font footer
{
get
{
// create a basecolor to use for the footer font, if needed.
iTextSharp.text.Color grey = new iTextSharp.text.Color(40, 40, 40);
Font font = FontFactory.GetFont("Arial", 16, iTextSharp.text.Font.BOLD, grey);
return font;
}
}
//override the OnPageEnd event handler to add our footer
public override void OnEndPage(PdfWriter writer, Document doc)
{
if (doc.PageNumber > 1)
{
//I use a PdfPtable with 2 columns to position my footer where I want it
PdfPTable footerTbl = new PdfPTable(2);
//set the width of the table to be the same as the document
footerTbl.TotalWidth = doc.PageSize.Width;
//Center the table on the page
footerTbl.HorizontalAlignment = Element.ALIGN_CENTER;
//Create a paragraph that contains the footer text
Paragraph para = new Paragraph(" ", footer);
//add a carriage return
para.Add(Environment.NewLine);
para.Add(" ");
//create a cell instance to hold the text
PdfPCell cell = new PdfPCell(para);
//set cell border to 0
cell.Border = 0;
//add some padding to bring away from the edge
cell.PaddingLeft = 10;
//add cell to table
footerTbl.AddCell(cell);
//create new instance of Paragraph for 2nd cell text
para = new Paragraph(" " + doc.PageNumber, footer);
//create new instance of cell to hold the text
cell = new PdfPCell(para);
//align the text to the right of the cell
cell.HorizontalAlignment = Element.ALIGN_LEFT;
//set border to 0
cell.Border = 0;
// add some padding to take away from the edge of the page
cell.PaddingRight = 10;
//add the cell to the table
footerTbl.AddCell(cell);
//write the rows out to the PDF output stream.
footerTbl.WriteSelectedRows(0, -1, 0, (doc.BottomMargin + 25), writer.DirectContent);
}
}
}
Thank you!
(writer.PageNumber - 1) is the last page. so check that too.
public class PageEventHelper : PdfPageEventHelper
{
PdfContentByte cb;
PdfTemplate template;
private int TotalNumber = 0;
//for remeber lastpage
public void SetNumber(int num)
{
TotalNumber = num;
}
public override void OnOpenDocument(PdfWriter writer, Document document)
{
cb = writer.DirectContent;
template = cb.CreateTemplate(50, 50);
}
public override void OnEndPage(PdfWriter writer, Document document)
{
base.OnEndPage(writer, document);
cb = writer.DirectContent;
template = cb.CreateTemplate(50, 50);
BaseFont font = BaseFont.CreateFont();
int pageN = writer.PageNumber;
String text = pageN.ToString();
float len = font.GetWidthPoint(text, 9);
iTextSharp.text.Rectangle pageSize = document.PageSize;
// cb.SetRGBColorFill(100, 100, 100);
;
cb.BeginText();
cb.SetFontAndSize(font, 9);
cb.SetTextMatrix(document.LeftMargin, pageSize.GetBottom(document.BottomMargin));
//cb.ShowText(text);
if (pageN > 1 && TotalNumber==0)
{
cb.ShowTextAligned(Element.ALIGN_CENTER, (pageN - 6).ToString() , 300f, 10f, 0);
}
cb.EndText();
cb.AddTemplate(template, document.LeftMargin + len, pageSize.GetBottom(document.BottomMargin));
}
}
And how to use the code ?
doc.Open();
//PdfWriter writer = PdfWriter.GetInstance(doc, stream);
PageEventHelper pageEventHelper = new PageEventHelper();
writer.PageEvent = pageEventHelper;
And before doc.closed()
Use the function SetNumber()
pageEventHelper.SetNumber(writer.PageNumber);
doc.Close();
you can use other number instead of the writer.PageNumber but not 0.
Hope this help you!

Categories