1

here is What i want i want to add page numbers to every pdf page that i generated on the fly.

i used on end page method but it did not worked out even when i added the doc bottom margin.

I decided to add the page numbers after the pdf is generated from the file path. here is my code for generating pdf:

Document doc = new Document(iTextSharp.text.PageSize.LETTER, 10, 10, 42, 35);



            PdfWriter wri = PdfWriter.GetInstance(doc, new FileStream("t5.pdf", FileMode.Create));

            doc.Open();//Open Document to write

          iTextSharp.text.Font font8 = FontFactory.GetFont("ARIAL", 7);
            Paragraph paragraph = new Paragraph("Some content");
            doc.Add(paragraph);
                doc.Add(paragraph);// add paragraph to the document
                doc.Close();
                FileStream stream = File.OpenRead("t5.pdf");
                byte[] fileBytes = new byte[stream.Length];
                stream.Read(fileBytes, 0, fileBytes.Length);
                stream.Close();
                AddPageNumbers(fileBytes);
                using (Stream file = File.OpenWrite("t5.pdf")) 
                {
                    file.Write(fileBytes, 0, fileBytes.Length);
                }
            }

and her is my add pagenumbers method:

MemoryStream ms = new MemoryStream();
        PdfReader reader = new PdfReader(pdf);
        int n = reader.NumberOfPages;
        iTextSharp.text.Rectangle psize = reader.GetPageSize(1);
        Document document = new Document(psize, 50, 50, 50, 50);
        PdfWriter writer = PdfWriter.GetInstance(document, ms);
        document.Open();
        PdfContentByte cb = writer.DirectContent;
        int p = 0;
        for (int page = 1; page <= reader.NumberOfPages; page++)
        {
            document.NewPage();
            p++;
            PdfImportedPage importedPage = writer.GetImportedPage(reader, page);
            cb.AddTemplate(importedPage, 0, 0);
            BaseFont bf = BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.NOT_EMBEDDED);
            cb.BeginText();
            cb.SetFontAndSize(bf, 10);
            cb.ShowTextAligned(PdfContentByte.ALIGN_CENTER, +p + "/" + n, 100, 450, 0);
            cb.EndText();
        }
        document.Close();
        return ms.ToArray();

how ever it does not add the page numbers to the pdf document so what is the alternatives here? what can i do.

user3786134
  • 361
  • 1
  • 6
  • 21

1 Answers1

6

When posting a question here, please only post the smallest amount of code possible. Your "create a sample PDF with multiple pages" is 116 lines long. Inside of it you've got complicated PdfPTable and DataTable logic that is 100% unrelated to the problem. Instead, the following 13 lines is enough to make a multiple page PDF:

//Create a sample multiple page PDF and place it on the desktop
var outputFile = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "t5.pdf");
using (var fs = new FileStream(outputFile, FileMode.Create, FileAccess.Write, FileShare.None)) {
    using (var doc = new Document()) {
        using (var writer = PdfWriter.GetInstance(doc, fs)) {
            doc.Open();
            for (var i = 0; i < 1000; i++) {
                doc.Add(new Paragraph(String.Format("This is paragraph #{0}", i)));
            }
            doc.Close();
        }
    }
}

Second, get rid of try/catch. Those are great for production (sometimes) but at the development level that's why we have IDEs and compilers, they'll tell us specifically what's wrong.

Now on to the bigger problem, you need to keep these two processes separate from each other. Every single brace and object from part part #1 must be closed, done and accounted for. Part #2 then needs to be fed a completely valid PDF but neither of the two parts should be "aware" of each other or depend on each other.

Since you just borrowed some code that wasn't intended for what you're trying to do I'm going to also ignore that and use some code that I know specifically will work. Also, since you're open to using a MemoryStream in the first place I'm just going to avoid writing to disk until I need to. Below is a full working sample that creates a multiple page and then adds page numbers in a second pass.

//Will hold our PDF as a byte array
Byte[] bytes;

//Create a sample multiple page PDF, nothing special here
using (var ms = new MemoryStream()) {
    using (var doc = new Document()) {
        using (var writer = PdfWriter.GetInstance(doc, ms)) {
            doc.Open();
            for (var i = 0; i < 1000; i++) {
                doc.Add(new Paragraph(String.Format("This is paragraph #{0}", i)));
            }
            doc.Close();
        }
    }
    //Store our bytes before
    bytes = ms.ToArray();
}

//Read our sample PDF and apply page numbers
using (var reader = new PdfReader(bytes)) {
    using (var ms = new MemoryStream()) {
        using (var stamper = new PdfStamper(reader, ms)) {
            int PageCount = reader.NumberOfPages;
            for (int i = 1; i <= PageCount; i++) {
                ColumnText.ShowTextAligned(stamper.GetOverContent(i), Element.ALIGN_CENTER, new Phrase(String.Format("Page {0} of {1}", i, PageCount)), 100, 10 , 0);
            }
        }
        bytes = ms.ToArray();
    }
}

var outputFile = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "t5.pdf");
System.IO.File.WriteAllBytes(outputFile, bytes);
Chris Haas
  • 53,986
  • 12
  • 141
  • 274
  • Hii, @Chris Haas , When I run your above code with creating just Sample PDF it is running perfectly but on another side when I am trying to run page number code pdf is not opening. – Hardik Parmar Nov 22 '16 at 14:29
  • Count of bytes in the Sample pdf is 3250 but in the page number PDF bytes are just 15. so something wrong with my code can you assume why it is doing like this. – Hardik Parmar Nov 22 '16 at 14:30