iTextSharp PageNumber but not on first and last pages - c#

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!

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

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

Generate a PDF file from two gridviews using iTextSharp

I use to generate a PDF file from a gridview using iTextSharp.
I need a help because I am not familiar with iTextSharp.
I'm using two gridviews in my aspx page: gvProducts and gvUsers.
The generation a PDF file from a single (gvProducts) gridview using iTextSharp working correctly.
I can't print the first and second GridView in the same PDF.
This is what I want:
Open PDF document;
Print result of my first GridView;
Print result of my second GridView;
Close, Save and download PDF document in the client.
Anybody know how can I do that?
Thank you in advance.
My code below.
protected void ExportToPDFWithFormatting()
{
//link button column is excluded from the list
int colCount = gvProducts.Columns.Count - 1;
//Create a table
PdfPTable table = new PdfPTable(colCount);
table.HorizontalAlignment = 1;
table.WidthPercentage = 100;
//create an array to store column widths
int[] colWidths = new int[gvProducts.Columns.Count];
PdfPCell cell;
string cellText;
//create the header row
for (int colIndex = 0; colIndex < colCount; colIndex++)
{
table.SetWidths(new int[] { 0, 40, 120, 110, 60, 60, 100, 90, 100, 50, 50, 50, 40, 30, 260, 200, 0 });
//fetch the header text
cellText = Server.HtmlDecode(gvProducts.HeaderRow.Cells[colIndex].Text);
//create a new cell with header text
BaseFont bf = BaseFont.CreateFont(
BaseFont.HELVETICA,
BaseFont.CP1252,
BaseFont.EMBEDDED,
false);
iTextSharp.text.Font font = new iTextSharp.text.Font(bf, 10, iTextSharp.text.Font.BOLD, BaseColor.WHITE);
cell = new PdfPCell(new Phrase(cellText.Replace("<br />", Environment.NewLine), font));
cell.HorizontalAlignment = Element.ALIGN_CENTER;
cell.VerticalAlignment = Element.ALIGN_MIDDLE;
cell.FixedHeight = 45f;
//set the background color for the header cell
cell.BackgroundColor = new BaseColor(System.Drawing.ColorTranslator.FromHtml("#a52a2a"));
//add the cell to the table. we dont need to create a row and add cells to the row
//since we set the column count of the table to 4, it will automatically create row for
//every 4 cells
table.AddCell(cell);
}
//export rows from GridView to table
for (int rowIndex = 0; rowIndex < gvProducts.Rows.Count; rowIndex++)
{
if (gvProducts.Rows[rowIndex].RowType == DataControlRowType.DataRow)
{
for (int j = 0; j < gvProducts.Columns.Count - 1; j++)
{
//fetch the column value of the current row
cellText = Server.HtmlDecode(gvProducts.Rows[rowIndex].Cells[j].Text);
//create a new cell with column value
cell = new PdfPCell(new Phrase(cellText, FontFactory.GetFont("PrepareForExport", 8)));
cell.HorizontalAlignment = Element.ALIGN_CENTER;
cell.VerticalAlignment = Element.ALIGN_MIDDLE;
cell.FixedHeight = 25f;
//Set Color of Alternating row
if (rowIndex % 2 != 0)
{
cell.BackgroundColor = new BaseColor(System.Drawing.ColorTranslator.FromHtml("#f5f5dc"));
}
else
{
cell.BackgroundColor = new BaseColor(System.Drawing.ColorTranslator.FromHtml("#fcfcfc"));
}
//add the cell to the table
table.AddCell(cell);
}
}
}
//Create the PDF Document
Document pdfDoc = new Document(PageSize.A3.Rotate(), 30f, 30f, 30f, 0f);
PdfWriter.GetInstance(pdfDoc, Response.OutputStream);
//open the stream
pdfDoc.Open();
table.HeaderRows = 1;
iTextSharp.text.Font fdefault = FontFactory.GetFont("Verdana", 18, iTextSharp.text.Font.BOLD, BaseColor.BLUE);
string s = "Report";
pdfDoc.Add(new Paragraph(s, fdefault));
//add the table to the document
pdfDoc.Add(table);
//close the document stream
pdfDoc.Close();
Response.ContentType = "application/pdf";
Response.AddHeader("content-disposition", "attachment;" + DateTime.Now + ".pdf");
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.Write(pdfDoc);
Response.End();
}
Edit #1
This is my code for generate pdf on GridView number two (gvUsers).
The code working but in the headers columns I have the names of GridView number one (gvProducts)... why?
//start pdf gridview number two
int colCountUsers = gvUsers.Columns.Count - 1;
PdfPTable tableUsers = new PdfPTable(colCountUsers);
tableUsers.HorizontalAlignment = 1;
tableUsers.WidthPercentage = 100;
int[] colWidthsUsers = new int[gvUsers.Columns.Count];
PdfPCell cellUsers;
string cellTextUsers;
for (int colIndexUsers = 0; colIndexUsers < colCountUsers; colIndexUsers++)
{
tableUsers.SetWidths(new int[] { 0, 40, 120, 110, 60, 60, 100 });
cellTextUsers = Server.HtmlDecode(gvProducts.HeaderRow.Cells[colIndexUsers].Text);
BaseFont bfUsers = BaseFont.CreateFont(
BaseFont.HELVETICA,
BaseFont.CP1252,
BaseFont.EMBEDDED,
false);
iTextSharp.text.Font fontUsers = new iTextSharp.text.Font(bfUsers, 10, iTextSharp.text.Font.BOLD, BaseColor.WHITE);
cellUsers = new PdfPCell(new Phrase(cellTextUsers.Replace("<br />", Environment.NewLine), fontUsers));
cellUsers.HorizontalAlignment = Element.ALIGN_CENTER;
cellUsers.VerticalAlignment = Element.ALIGN_MIDDLE;
cellUsers.FixedHeight = 45f;
cellUsers.BackgroundColor = new BaseColor(System.Drawing.ColorTranslator.FromHtml("#a52a2a"));
tableUsers.AddCell(cellUsers);
}
for (int rowIndexUsers = 0; rowIndexUsers < gvUsers.Rows.Count; rowIndexUsers++)
{
if (gvUsers.Rows[rowIndexUsers].RowType == DataControlRowType.DataRow)
{
for (int j = 0; j < gvUsers.Columns.Count - 1; j++)
{
cellTextUsers = Server.HtmlDecode(gvUsers.Rows[rowIndexUsers].Cells[j].Text);
cellUsers = new PdfPCell(new Phrase(cellTextUsers, FontFactory.GetFont("PrepareForExport", 8)));
cellUsers.HorizontalAlignment = Element.ALIGN_CENTER;
cellUsers.VerticalAlignment = Element.ALIGN_MIDDLE;
cellUsers.FixedHeight = 25f;
tableUsers.AddCell(cellUsers);
}
}
}
Document pdfDocUsers = new Document(PageSize.A3.Rotate(), 30f, 30f, 30f, 0f);
PdfWriter.GetInstance(pdfDocUsers, Response.OutputStream);
pdfDocUsers.Open();
tableUsers.HeaderRows = 1;
iTextSharp.text.Font fdefaultUsers = FontFactory.GetFont("Verdana", 18, iTextSharp.text.Font.BOLD, BaseColor.BLUE);
string sUsers = "Users";
pdfDocUsers.Add(new Paragraph(sUsers, fdefaultUsers));
pdfDocUsers.Add(tableUsers);
pdfDocUsers.Close();
//end pdf gridview number two
//in first pdf gridview
//add the table to the document
pdfDoc.Add(table);
pdfDoc.Add(tableUsers);
int colCount1 = gvProducts1.Columns.Count - 1;
//Create a table
PdfPTable table1 = new PdfPTable(colCount1);
table1.HorizontalAlignment = 1;
table1.WidthPercentage = 100;
//create an array to store column widths
int[] colWidths1 = new int[gvProducts1.Columns.Count];
PdfPCell cell1;
string cellText1;
//create the header row
for (int colIndex1 = 0; colIndex1 < colCount1; colIndex1++)
{
table1.SetWidths(new int[] { 0, 40, 120, 110, 60, 60, 100, 90, 100, 50, 50, 50, 40, 30, 260, 200, 0 });
//fetch the header text
cellText1 = Server.HtmlDecode(gvProducts1.HeaderRow.Cells[colIndex1].Text);
//create a new cell with header text
BaseFont bf1 = BaseFont.CreateFont(
BaseFont.HELVETICA,
BaseFont.CP1252,
BaseFont.EMBEDDED,
false);
iTextSharp.text.Font font1 = new iTextSharp.text.Font(bf, 10, iTextSharp.text.Font.BOLD, BaseColor.WHITE);
cell1 = new PdfPCell(new Phrase(cellText.Replace("<br />", Environment.NewLine), font));
cell1.HorizontalAlignment = Element.ALIGN_CENTER;
cell1.VerticalAlignment = Element.ALIGN_MIDDLE;
cell1.FixedHeight = 45f;
//set the background color for the header cell
cell1.BackgroundColor = new BaseColor(System.Drawing.ColorTranslator.FromHtml("#a52a2a"));
//add the cell to the table. we dont need to create a row and add cells to the row
//since we set the column count of the table to 4, it will automatically create row for
//every 4 cells
table1.AddCell(cell1);
}
//export rows from GridView to table
for (int rowIndex1 = 0; rowIndex1 < gvProducts1.Rows.Count; rowIndex1++)
{
if (gvProducts.Rows[rowIndex1].RowType == DataControlRowType.DataRow)
{
for (int j1 = 0; j1 < gvProducts1.Columns.Count - 1; j1++)
{
//fetch the column value of the current row
cellText1 = Server.HtmlDecode(gvProducts1.Rows[rowIndex1].Cells[j].Text);
//create a new cell with column value
cell1 = new PdfPCell(new Phrase(cellText1, FontFactory.GetFont("PrepareForExport", 8)));
cell1.HorizontalAlignment = Element.ALIGN_CENTER;
cell1.VerticalAlignment = Element.ALIGN_MIDDLE;
cell1.FixedHeight = 25f;
//Set Color of Alternating row
if (rowIndex1 % 2 != 0)
{
cell1.BackgroundColor = new BaseColor(System.Drawing.ColorTranslator.FromHtml("#f5f5dc"));
}
else
{
cell1.BackgroundColor = new BaseColor(System.Drawing.ColorTranslator.FromHtml("#fcfcfc"));
}
//add the cell to the table
table1.AddCell(cell1);
}
}
}
//Create the PDF Document
//open the stream
//add the table to the document
pdfDoc.Add(table1);
//close the document stream
pdfDoc.Close();
Response.ContentType = "application/pdf";
Response.AddHeader("content-disposition", "attachment;" + DateTime.Now + ".pdf");
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.Write(pdfDoc);
Response.End();

iTextSharp SetCharacterSpacing broken when using Right Align

I have a table with two cells. The first cell is left aligned and the second cell is right aligned. I also want to change the character spacing of the text. I have found that changing the character spacing breaks the alignment so the right align text ends up outside the boundaries if the table.
I have created some test code below and the link to the output PDF is in this link
https://skydrive.live.com/redir?resid=1ECE2061CFF9124B!190&authkey=!ANcB0z_BN3N4UFo
Are there any alternatives or workarounds to getting the character spacing working well with the right alignment?
public void CharacterSpacingTest()
{
float margin = 50;
using (var stream = new MemoryStream())
{
Document document = new Document();
document.SetPageSize(new Rectangle(PageSize.A4.Width, PageSize.A4.Height));
document.SetMargins(margin, margin, 30f, 100f);
PdfWriter writer = PdfWriter.GetInstance(document, stream);
writer.CloseStream = false;
document.Open();
PdfPTable table = new PdfPTable(new float[] { 100 });
table.TotalWidth = PageSize.A4.Width - margin - margin;
table.WidthPercentage = 100f;
table.LockedWidth = true;
// Create a row that is right aligned
PdfPCell cell1 = new PdfPCell();
cell1.AddElement(new Paragraph("Hello World") { Alignment = Element.ALIGN_RIGHT });
cell1.BorderWidth = 1;
table.AddCell(cell1);
// Change the character spacing
PdfContentByte cb = writer.DirectContent;
cb.SetCharacterSpacing(1f);
// Create a row that is left aligned
PdfPCell cell2 = new PdfPCell();
cell2.AddElement(new Paragraph("Hello World"));
cell2.BorderWidth = 1;
table.AddCell(cell2);
document.Add(table);
document.Close();
Blobs.SaveToFile(Blobs.LoadFromStream(stream), #"c:\Dev\test.pdf");
}
}
I have managed to fix it by using chunks to set the character spacing. See amended code.
public void CharacterSpacingTest()
{
float margin = 50;
using (var stream = new MemoryStream())
{
Document document = new Document();
document.SetPageSize(new Rectangle(PageSize.A4.Width, PageSize.A4.Height));
document.SetMargins(margin, margin, 30f, 100f);
PdfWriter writer = PdfWriter.GetInstance(document, stream);
writer.CloseStream = false;
document.Open();
PdfPTable table = new PdfPTable(new float[] { 100 });
table.TotalWidth = PageSize.A4.Width - margin - margin;
table.WidthPercentage = 100f;
table.LockedWidth = true;
// Create a row that is right aligned
PdfPCell cell1 = new PdfPCell();
cell1.AddElement(new Paragraph(GetChunk("Hello World")) { Alignment = Element.ALIGN_RIGHT });
cell1.BorderWidth = 1;
table.AddCell(cell1);
// Create a row that is left aligned
PdfPCell cell2 = new PdfPCell();
cell2.AddElement(new Paragraph(GetChunk("Hello World")));
cell2.BorderWidth = 1;
table.AddCell(cell2);
document.Add(table);
document.Close();
Blobs.SaveToFile(Blobs.LoadFromStream(stream), #"c:\Dev\test.pdf");
}
}
private Chunk GetChunk(string text)
{
Chunk chunk = new Chunk(text);
chunk.SetCharacterSpacing(1);
return chunk;
}

Categories