Place pagination when generating PDF with iTextSharp

0

I'm using iTextSharp to generate PDF's in my application. Now a problem has arisen: I am printing listings and when there is more than one page I would like to print a footer with page numbers (eg "Page 1 of 4"). I found some examples but they seem more complex than necessary (like example ).

EDIT: I started following this example 2 , however I am not able to print the numbering . Code:

    public ActionResult downloadListaISCC(DateTime? DataFimFiltro)
    {
    //Código para gerar a lista a apresentar

    //Definir tipo de documento
    Document doc1 = new Document();
    doc1.SetPageSize(iTextSharp.text.PageSize.A4);
    doc1.SetMargins(0f, 0f, 0f, 0f);
    doc1.NewPage();

    MemoryStream pdfStream = new MemoryStream();
    PdfWriter pdfWriter = PdfWriter.GetInstance(doc1, pdfStream);

    //gerar a tabela e adicionar ao doc1
    pdfWriter.CloseStream = true;
    doc1.Close();

   //E fui seguindo o exemplo do segundo link
   string file = "D:/gerarPDFOleotorres/"+ nomeDoc +""; 

   // add page numbers
   Document copyDoc = new Document();
   PdfCopy copyPdf = new PdfCopy(copyDoc, new FileStream(file, FileMode.Create));
   copyPdf.SetPageSize(PageSize.A4.Rotate());
   copyDoc.Open();

   // read the initial pdf document
   PdfReader reader = new PdfReader(pdfStream.ToArray());
   int totalPages = reader.NumberOfPages;

   PdfImportedPage copiedPage = null;
   iTextSharp.text.pdf.PdfCopy.PageStamp stamper = null;

   for (int i = 0; i < totalPages; i++)
   {

       // get the page and create a stamper for that page
       copiedPage = copyPdf.GetImportedPage(reader, (i + 1));
       stamper = copyPdf.CreatePageStamp(copiedPage);

       // add a page number to the page
       ColumnText.ShowTextAligned(stamper.GetUnderContent(), Element.ALIGN_CENTER, new Phrase((i + 1) + "/" + totalPages, fontetexto), 820f, 15, 0);
        stamper.AlterContents();

       // add the altered page to the new document
       copyPdf.AddPage(copiedPage);
   }

   copyDoc.Close();
   reader.Close();

   // flush and clear the document from memory
   pdfStream.Flush();
   pdfStream.Close();
    }

It correctly detects the number of pages but is not printing

    
asked by anonymous 02.04.2014 / 10:49

1 answer

2

One solution is to create the file in 2 steps: In the first one it creates everything except footer , and in the second step this file is opened to know the total of pages and it is written footer . >

Example

    
02.04.2014 / 12:14