0

I'm trying to generate a PDF file using iTextSharp, so I managed to generate my PDF files as below:

enter image description here

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, ...

AHmedRef
  • 2,555
  • 12
  • 43
  • 75
  • 1
    Have a look at this Java example : http://itextpdf.com/examples/iia.php?id=118 . Translating it to C# should be trivial. – Alexis Pigeon Oct 22 '14 at 09:58
  • thanks for your solution, but i wanna create header and footer for every page of document, i don't means table header/footer. – AHmedRef Oct 22 '14 at 10:01
  • 1
    I see you added the Tags in the title again. On StackOverflow the consens is: [tags do not belong in the title](http://meta.stackexchange.com/questions/19190/should-questions-include-tags-in-their-titles). Please keep that in mind for future questions you might ask. :) – waka Oct 22 '14 at 10:51
  • 1
    @AHmédNet and that's exactly what this example is about : for each page, it displays the title (`FOOBAR FILMFESTIVAL`) and `Page X of Y`. – Alexis Pigeon Oct 22 '14 at 11:21
  • 1
    Please never post that much code, you should only post as much as you need so that everyone can reproduce and/or understand your issue. Also, and I'm not going to read all 220 lines but as far as I can tell none of your code posted is even related to your actual question except possibly the two lines of comment showing where you think the header and footer logic should go. – Chris Haas Oct 22 '14 at 13:41
  • 1
    possible duplicate of [Page X of Y issue](http://stackoverflow.com/questions/9845367/page-x-of-y-issue) – Chris Haas Oct 22 '14 at 13:43

1 Answers1

0

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.

NottsCoder
  • 11
  • 3