iTextSharp set dynamic margins - c#

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 };
}
}
}

Related

Get total number of pages in iTextsharp PDF 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();
}
}

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.

How to add a table in absolute position at the beginning of the page using iTextSharp?

I have a class named PdfHeaderFooter that extends PdfPageEventHelper class.
In this class I have implemented the OnEndPage() method in this way. How you can see this method create the header and the footer of each pages of the document.
Now I have to add the PdfPTable tabHead in absolute position at the beginning of the page.
What can I have to do? I am going crazy trying to do it
// write on end of each page
public override void OnEndPage(PdfWriter writer, Document document)
{
base.OnEndPage(writer, document);
// HEADER:
PdfPTable tabHead = new PdfPTable(3);
tabHead.SetWidths(new int[] { 165, 205, 125 });
//tabHead.TotalWidth = 460F;
tabHead.TotalWidth = document.Right - document.Left; // TotalWidth = 495
tabHead.WidthPercentage = 98;
PdfPCell cell1 = new PdfPCell(iTextSharp.text.Image.GetInstance(folderImages + "logoEarlyWarning.png"), true) { Border = PdfPCell.BOTTOM_BORDER };
tabHead.AddCell(cell1);
//tabHead.AddCell(new PdfPCell(new Phrase("CELL 1:")) { Border = PdfPCell.BOTTOM_BORDER, Padding = 5, MinimumHeight = 50, PaddingTop = 15, });
tabHead.AddCell(new PdfPCell(new Phrase("")) { Border = PdfPCell.BOTTOM_BORDER, Padding = 5, MinimumHeight = 50, PaddingTop = 15 });
if (_sourceId == "NVD")
{
iTextSharp.text.Image logo = iTextSharp.text.Image.GetInstance(folderImages + "nvdLogo.png");
logo.ScalePercent(48f);
//PdfPCell cell3 = new PdfPCell(iTextSharp.text.Image.GetInstance(folderImages + "nvdLogo.png"), true) { Border = PdfPCell.BOTTOM_BORDER, PaddingBottom = 25 };
PdfPCell cell3 = new PdfPCell(logo) { Border = PdfPCell.BOTTOM_BORDER, PaddingLeft = 50 };
tabHead.AddCell(cell3);
}
else if (_sourceId == "DeepSight")
{
PdfPCell cell3 = new PdfPCell(iTextSharp.text.Image.GetInstance(folderImages + "DSLogo.jpg"), true) { Border = PdfPCell.BOTTOM_BORDER };
tabHead.AddCell(cell3);
}
//tabHead.AddCell(new PdfPCell(new Phrase("CELL 3:")) { Border = PdfPCell.BOTTOM_BORDER, Padding = 5, MinimumHeight = 50, PaddingTop = 15 });
tabHead.WriteSelectedRows(0, -1, document.Left, document.Top, writer.DirectContent);
float headerHeight = tabHead.CalculateHeights();
// FOOTER:
int pageN = writer.PageNumber; // numero della pagina corrente OK
String text = "Page " + pageN + " of ";
float len = bf.GetWidthPoint(text, 8);
Rectangle pageSize = document.PageSize;
cb.SetRGBColorFill(100, 100, 100);
cb.BeginText();
cb.SetFontAndSize(bf, 8);
cb.SetTextMatrix(pageSize.GetLeft(40), pageSize.GetBottom(30));
cb.ShowText(text);
cb.EndText();
cb.AddTemplate(template, pageSize.GetLeft(40) + len, pageSize.GetBottom(30));
cb.BeginText();
cb.SetFontAndSize(bf, 8);
cb.ShowTextAligned(PdfContentByte.ALIGN_RIGHT,
"Printed On " + PrintTime,
pageSize.GetRight(40),
pageSize.GetBottom(30), 0);
cb.EndText();
}
Tnx
This question has already been answered here: How to handle the case in wich an iText\iTextSharp table is splitted in two pages?
You are adding the header at the beginning of the page, taking into account the margin. You want to add the table inside the margin. hence you need to add the height of the table to the Y-coordinate of the upper margin.
For instance: if the height of the table is h, then you need:
tabHead.WriteSelectedRows(0, -1, document.Left, document.Top + h, writer.DirectContent);
What's the point in asking questions if you don't read people's answers? You're still generating a bloated PDF file! Fix that!

print an icard in pdf using itextsharp

I want to create a PDF file with Icard showing in it.
Following is the code:
iTextSharp.text.Font custFont = new iTextSharp.text.Font() { Size=6f};
int borderSize = 1;
Document IcardDoc = new Document(PageSize.HALFLETTER);
PdfWriter.GetInstance(IcardDoc, Response.OutputStream);
IcardDoc.Open();
PdfPTable icardTable = new PdfPTable(2);
iTextSharp.text.Image logoImage = iTextSharp.text.Image.GetInstance(Server.MapPath("~/images/logo.jpg"));
logoImage.WidthPercentage = 15f;
PdfPCell cell = new PdfPCell(logoImage, false);
cell.PaddingLeft = 10f;
cell.PaddingTop = 10f;
cell.PaddingBottom = 10f;
cell.PaddingRight = 10f;
cell.Colspan = 2;
cell.Border = 0;
cell.HorizontalAlignment = 1;
icardTable.AddCell(cell);
icardTable.AddCell(new PdfPCell(new Phrase("Name:", custFont)) { Border = borderSize });
icardTable.AddCell(new PdfPCell(new Phrase(student.firstname + " " + student.lastname, custFont)) { Border = borderSize });
The print document size will be 8.5 cm in height and 5.4 cm in width.
So need to fit it that way, is there any solution to this because the above code is not fitting the table on page and in proper size?
Any other format will also do like word etc.
figured out the solution :
Document IcardDoc = new Document(new Retangele(200f, 315f),35f,35f,0f,0f);
and adjust the width of the table accordingly:
PdfPTable icardTable = new PdfPTable(2);
icardTable.WidthPercentage = 140f;
to fit table exactly on page, if decrease rectangle width then increase table WidthPercentage and vice versa.
You also need to care of left and right margins defined as 35f in Document class constructor
This worked for me.
var pgSize = new iTextSharp.text.Rectangle(1042, 651);
var doc = new iTextSharp.text.Document(pgSize, 0, 0, 0, 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