how to add pagenumbers to every pdf page using itextsharp

user3786134

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.

Chris Haas

Sorry, lecture comes first.

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

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

From Dev

How do I add XMP metadata to each page of an existing PDF using iTextSharp

From Dev

converting repeater control to pdf using itextsharp every repeated contents should come in new page

From Dev

converting repeater control to pdf using itextsharp every repeated contents should come in new page

From Dev

ITextSharp add page numbers to merged pdf

From Dev

How to break pdf page in itextsharp pdf

From Dev

Add Page bookmarks to an existing PDF using iTextSharp using C# code

From Dev

Add Page bookmarks to an existing PDF using iTextSharp using C# code

From Dev

Add a Header to Every Page in a PDF?

From Dev

Is it possible to convert PDF page to Image using itextSharp?

From Dev

Add javascript to pdf file using iTextSharp

From Dev

Add javascript to pdf file using iTextSharp

From Dev

How to Stamp PDF with another PDF using iTextSharp

From Dev

How to Stamp PDF with another PDF using iTextSharp

From Dev

iTextSharp: How to add image of PDF as movable element?

From Dev

How to add list of lists of string in PDF with iTextSharp?

From Dev

How to add list of lists of string in PDF with iTextSharp?

From Dev

iTextSharp how to Add and Extract image to existing PDF

From Dev

itextsharp: How to generate a report with dynamic header in PDF using itextsharp?

From Dev

How can I combine multiple PDF files excluding page breaks using iTextSharp?

From Java

How to convert HTML to PDF using iTextSharp

From Dev

How to open a pdf file using itextsharp

From Dev

how to get pdf image orientation using itextsharp

From Dev

How do I add a footer in a PDF using iTextSharp VB.net?

From Dev

Find location last object on PDF page using iTextSharp

From Dev

Trying to add a PDF stamp using iTextSharp, "The byte array is not a recognized imageformat"

From Dev

Add signature image on PDF without digitally signing it using iTextSharp

From Dev

How to add text in PdfContentByte rectangle using itextsharp?

From Dev

iTextSharp - PDF Bookmark not pointing to a page

From Dev

How to add height at the top and bottom of PDF page using PdfSharp?

Related Related

  1. 1

    How do I add XMP metadata to each page of an existing PDF using iTextSharp

  2. 2

    converting repeater control to pdf using itextsharp every repeated contents should come in new page

  3. 3

    converting repeater control to pdf using itextsharp every repeated contents should come in new page

  4. 4

    ITextSharp add page numbers to merged pdf

  5. 5

    How to break pdf page in itextsharp pdf

  6. 6

    Add Page bookmarks to an existing PDF using iTextSharp using C# code

  7. 7

    Add Page bookmarks to an existing PDF using iTextSharp using C# code

  8. 8

    Add a Header to Every Page in a PDF?

  9. 9

    Is it possible to convert PDF page to Image using itextSharp?

  10. 10

    Add javascript to pdf file using iTextSharp

  11. 11

    Add javascript to pdf file using iTextSharp

  12. 12

    How to Stamp PDF with another PDF using iTextSharp

  13. 13

    How to Stamp PDF with another PDF using iTextSharp

  14. 14

    iTextSharp: How to add image of PDF as movable element?

  15. 15

    How to add list of lists of string in PDF with iTextSharp?

  16. 16

    How to add list of lists of string in PDF with iTextSharp?

  17. 17

    iTextSharp how to Add and Extract image to existing PDF

  18. 18

    itextsharp: How to generate a report with dynamic header in PDF using itextsharp?

  19. 19

    How can I combine multiple PDF files excluding page breaks using iTextSharp?

  20. 20

    How to convert HTML to PDF using iTextSharp

  21. 21

    How to open a pdf file using itextsharp

  22. 22

    how to get pdf image orientation using itextsharp

  23. 23

    How do I add a footer in a PDF using iTextSharp VB.net?

  24. 24

    Find location last object on PDF page using iTextSharp

  25. 25

    Trying to add a PDF stamp using iTextSharp, "The byte array is not a recognized imageformat"

  26. 26

    Add signature image on PDF without digitally signing it using iTextSharp

  27. 27

    How to add text in PdfContentByte rectangle using itextsharp?

  28. 28

    iTextSharp - PDF Bookmark not pointing to a page

  29. 29

    How to add height at the top and bottom of PDF page using PdfSharp?

HotTag

Archive