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.
Related
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();
}
}
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 };
I am using iText to export GridView to pdf.
I was able to add header color to my pdf.
I would like to add background color to the last (total) line/row of pdf in the Gridview?
I am using iText library to export GridView to Pdf.
Here is my pdf function :
public void ExpToPdf_Click(object sender, EventArgs e)
{
getHTMLGridView();
}
private void getHTMLGridView()
{
BaseFont bfTimes = BaseFont.CreateFont(BaseFont.TIMES_ROMAN, BaseFont.CP1252, false);
iTextSharp.text.Font times16 = new iTextSharp.text.Font(bfTimes, 16, iTextSharp.text.Font.NORMAL, iTextSharp.text.Color.BLACK);
Paragraph p1 = new Paragraph("Texas Tech University", times16);
p1.Alignment = 1;
iTextSharp.text.Font times14 = new iTextSharp.text.Font(bfTimes, 14, iTextSharp.text.Font.NORMAL, iTextSharp.text.Color.BLACK);
Paragraph p2 = new Paragraph("Department of Institutional Research", times14);
Paragraph p3 = new Paragraph(caption.Text.ToUpper(), times14);
p2.Alignment = 1;
p3.Alignment = 1;
//iTextSharp.text.Font times10 = new iTextSharp.text.Font(bfTimes, 10, iTextSharp.text.Font.NORMAL, iTextSharp.text.Color.BLACK);
//Paragraph p4 = new Paragraph("(Uncertified Data)", times10);
//p4.Alignment = 1;
Paragraph p5 = new Paragraph(" ");
iTextSharp.text.Font times8 = new iTextSharp.text.Font(bfTimes, 8, iTextSharp.text.Font.NORMAL, iTextSharp.text.Color.BLACK);
iTextSharp.text.Font times11 = new iTextSharp.text.Font(bfTimes, 10, iTextSharp.text.Font.NORMAL, iTextSharp.text.Color.WHITE);
iTextSharp.text.Color BackgroundColor = new iTextSharp.text.Color(System.Drawing.ColorTranslator.FromHtml("#CC0000"));
PdfPTable HeaderTable = new PdfPTable(4);
//actual width of table in points
HeaderTable.TotalWidth = 600f;
//fix the absolute width of the table
HeaderTable.LockedWidth = true;
//relative col widths in proportions - 1/3 and 2/3
float[] Headerwidths = new float[] { 1f, 1f, 1f, 1f};
HeaderTable.SetWidths(Headerwidths);
HeaderTable.HorizontalAlignment = 1;
//leave a gap before and after the table
//HeaderTable.SpacingBefore = 30f;
//HeaderTable.SpacingAfter = 30f;
foreach (TableCell cell in MyGridView.HeaderRow.Cells)
{
PdfPCell pdfCell = new PdfPCell(new Phrase(cell.Text, times11));
// Set the PDF cell backgroundcolor to GridView header row BackgroundColor color
pdfCell.BackgroundColor = BackgroundColor;
pdfCell.HorizontalAlignment = 1; //0=Left, 1=Centre, 2=Right
// Add the cell to PDF table
HeaderTable.AddCell(pdfCell);
}
PdfPTable table = new PdfPTable(4);
//actual width of table in points
table.TotalWidth = 600f;
//fix the absolute width of the table
table.LockedWidth = true;
//relative col widths in proportions
float[] widths = new float[] { 1f, 1f, 1f, 1f};
table.SetWidths(widths);
table.HorizontalAlignment = 1;
//leave a gap before and after the table
//table.SpacingBefore = 30f;
//table.SpacingAfter = 30f;
string connect = System.Web.Configuration.WebConfigurationManager.ConnectionStrings["ConnStringExtracts_IRDW"].ConnectionString;
DataSet ds = new DataSet();
using (SqlConnection conn = new SqlConnection(connect))
{
string query = "dbo.sp_FB_APPADM_IRDW";
SqlCommand cmd = new SqlCommand(query, conn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#reportType", reportType);
cmd.Parameters.AddWithValue("#term_Code", ENRDropDownList.SelectedValue);
try
{
int i;
conn.Open();
SqlDataAdapter adapter = new SqlDataAdapter(cmd);
// Fill the DataSet.
adapter.Fill(ds);
foreach (DataRow row in ds.Tables[0].Rows)
{
for (i = 0; i < 2; i++)
{
PdfPCell pdfCell4 = new PdfPCell(new Phrase(row[i].ToString(), times8));
pdfCell4.HorizontalAlignment = 0; //0=Left, 1=Centre, 2=Right
// Add the cell to PDF table
table.AddCell(pdfCell4);
}
for (i = 2; i < ds.Tables[0].Columns.Count; i++)
{
PdfPCell pdfCell4 = new PdfPCell(new Phrase(row[i].ToString(), times8));
pdfCell4.HorizontalAlignment = 2; //0=Left, 1=Centre, 2=Right
// Add the cell to PDF table
table.AddCell(pdfCell4);
}
}
}
catch (Exception ex)
{
Response.Write(ex.Message);
}
//Create the PDF Document
Document pdfDoc = new Document(PageSize.A4, 10f, 10f, 10f, 0f);
pdfDoc.SetPageSize(iTextSharp.text.PageSize.A4.Rotate());
PdfWriter.GetInstance(pdfDoc, Response.OutputStream);
//open the stream
pdfDoc.Open();
//add the table to the document
pdfDoc.Add(p1);
pdfDoc.Add(p2);
pdfDoc.Add(p3);
pdfDoc.Add(p5);
pdfDoc.Add(HeaderTable);
pdfDoc.Add(table);
//close the document stream
pdfDoc.Close();
Response.ContentType = "application/pdf";
Response.AddHeader("content-disposition", "attachment;" + "filename=Enrollment_Major_Classification.pdf");
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.Write(pdfDoc);
Response.End();
}
}
I tried using: GridView1.Rows[GridView1.Rows.Count - 1] to get the last row of gridview. But, I did not seem to make my way around it, to add color to last row.
Any help much appreciated.
You can simply do this:
GridView1.Rows[GridView1.Rows.Count - 1].BackColor = Color.Green;
Or if the row is a FooterRow:
GridView1.FooterRow.BackColor = Color.Red;
I'm attempting to create a PDF from a DataGridView populated from a database.
I have just started trying to learn how to use iTextSharp to accomplish this.
The result of my code is a PDF that will not open. I get an error saying "File cannot be opened"
Here is my code to generate the PDF
void SendToPDF(string heading, string filename)
{
try
{
Document doc = new Document(PageSize.A4.Rotate(), 30, 30, 20, 20);
string myDocs = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
if (!Directory.Exists(myDocs + #"\Production Reports"))
Directory.CreateDirectory(myDocs + #"\Production Reports");
PdfWriter.GetInstance(doc, new FileStream(myDocs + #"\Production Reports\" + filename + ".pdf", FileMode.Append, FileAccess.Write));
iTextSharp.text.Font titleFont = new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.HELVETICA, 14.0F, iTextSharp.text.Font.BOLD, BaseColor.BLACK);
iTextSharp.text.Font tableFont = new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.HELVETICA, 12.0F, iTextSharp.text.Font.NORMAL, BaseColor.BLACK);
iTextSharp.text.Font headerfont = new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.HELVETICA, 12.0F, iTextSharp.text.Font.BOLD, BaseColor.BLACK);
PdfPTable table = new PdfPTable(GridView.Columns.Count);
//table.TotalWidth = GridView.Width;
//There are ALWAYS 10 columns
float[] widths = new float[] { GridView.Columns[0].Width, GridView.Columns[1].Width, GridView.Columns[2].Width,
GridView.Columns[3].Width, GridView.Columns[4].Width, GridView.Columns[5].Width,
GridView.Columns[6].Width, GridView.Columns[7].Width, GridView.Columns[8].Width,
GridView.Columns[9].Width };
table.SetWidths(widths);
table.HorizontalAlignment = 1; // 0 - left, 1 - center, 2 - right;
table.SpacingBefore = 2.0F;
PdfPCell cell = null;
doc.Open();
Phrase p = new Phrase(new Chunk(heading, titleFont));
doc.Add(p);
foreach (DataGridViewColumn c in GridView.Columns)
{
cell = new PdfPCell(new Phrase(new Chunk(c.HeaderText, headerfont)));
cell.HorizontalAlignment = PdfPCell.ALIGN_CENTER;
cell.VerticalAlignment = PdfPCell.ALIGN_CENTER;
table.AddCell(cell);
}
if (GridView.Rows.Count > 0)
{
for (int i = 0; i < GridView.Rows.Count - 1; i++)
{
for (int j = 0; j < GridView.Columns.Count - 1; j++)
{
cell = new PdfPCell(new Phrase(GridView.Rows[i].Cells[j].Value.ToString(), tableFont));
cell.HorizontalAlignment = PdfPCell.ALIGN_CENTER;
cell.VerticalAlignment = PdfPCell.ALIGN_CENTER;
table.AddCell(cell);
}
}
}
doc.Add(table);
doc.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message + "\r\n" + ex.StackTrace, "Error Generating PDF", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
I'm guessing my problem has to do with setting column widths, but I'm not sure. One time, and only one time..I saw an error when I tried to open the PDF that said "illegal floating point division by 0" or something along those lines.
Any help is greatly appreciated.
It may sound obvious, but your program isn't running and locking the pdf file to its process thus preventing adobe pdf reader from reading it is it?
private void jbtnPdf_Click(object sender, EventArgs e)
{
try
{
SaveFileDialog saveFileDialog = new SaveFileDialog();
saveFileDialog.Filter = "All Files | *.* ";
if (saveFileDialog.ShowDialog() == DialogResult.OK)
{
string path = saveFileDialog.FileName;
Document pdfdoc = new Document(PageSize.A4); // Setting the page size for the PDF
PdfWriter writer = PdfWriter.GetInstance(pdfdoc, new FileStream(path + ".pdf", FileMode.Create)); //Using the PDF Writer class to generate the PDF
writer.PageEvent = new PDFFooter();
// Opening the PDF to write the data from the textbox
PdfPTable table = new PdfPTable(jdgvChild.Columns.Count);
//table.TotalWidth = GridView.Width;
float[] widths = new float[] { jdgvChild.Columns[0].Width, jdgvChild.Columns[1].Width, jdgvChild.Columns[2].Width,
jdgvChild.Columns[3].Width, jdgvChild.Columns[4].Width, jdgvChild.Columns[5].Width,
jdgvChild.Columns[6].Width, jdgvChild.Columns[7].Width};
table.SetWidths(widths);
table.HorizontalAlignment = 1; // 0 - left, 1 - center, 2 - right;
table.SpacingBefore = 2.0F;
PdfPCell cell = null;
pdfdoc.Open();
//doc.Open();
// Phrase p = new Phrase(new Chunk(heading, titleFont));
// doc.Add(p);
foreach (GridViewDataColumn c in jdgvChild.Columns)
{
cell = new PdfPCell(new Phrase(new Chunk(c.HeaderText)));
cell.HorizontalAlignment = PdfPCell.ALIGN_CENTER;
cell.VerticalAlignment = PdfPCell.ALIGN_CENTER;
table.AddCell(cell);
}
if (jdgvChild.Rows.Count > 0)
{
for (int i = 0; i < jdgvChild.Rows.Count; i++)
{
PdfPCell[] objcell = new PdfPCell[jdgvChild.Columns.Count];
for (int j = 0; j < jdgvChild.Columns.Count-1; j++)
{
cell = new PdfPCell(new Phrase(jdgvChild.Rows[i].Cells[j].Value.ToString()));
cell.HorizontalAlignment = PdfPCell.ALIGN_CENTER;
cell.VerticalAlignment = PdfPCell.ALIGN_CENTER;
// table.AddCell(cell);
//lstCells.Add(cell);
objcell[j] = cell;
}
PdfPRow newrow = new PdfPRow(objcell);
table.Rows.Add(newrow);
}
}
pdfdoc.Add(table);
MessageBox.Show("Pdf Generation Successfully.");
pdfdoc.Close();
}
}
catch (Exception ex)
{
MessageBox.Show("Error in pdf Generation.");
}
}
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!