0

I’ve a requirement where I need to generate a PDF file with Index along with Page numbers. I'm using ItextSharp for generating PDF. The Document may contains hundreds of pages. The data in the PDF document will be the dynamic data. Here is my Code to generate the PDF :

Rectangle rec2 = new Rectangle(PageSize.A4);
using (FileStream fs = new FileStream("D:/Sample1.pdf", FileMode.Create, FileAccess.Write, FileShare.None))
using (Document doc = new Document(PageSize.A4, 10f, 10f, 10f, 10f))
using (PdfWriter writer = PdfWriter.GetInstance(doc, fs))
{
       PdfPageEventHelper pageEventHelper = new PdfPageEventHelper();
       writer.PageEvent = pageEventHelper;
       doc.SetMargins(20, 20, 50, 50);
       doc.NewPage();
       doc.Open();
       var Content = writer.DirectContent;
       var pageBorderRect = new Rectangle(doc.PageSize);
       ………..
       ………………..
       ………………..
       ………..
       doc.Close();
}

And to add the page numbers to generated document I used the following method

public void AddPageNumber(string BidNumber)
        {
            byte[] bytes = System.IO.File.ReadAllBytes(@"D:\Sample1.pdf");
            Font blackFont = FontFactory.GetFont("Arial", 12, Font.NORMAL, BaseColor.BLACK);
            Font boldfont = FontFactory.GetFont("Arial", 14, Font.BOLD, BaseColor.BLACK);
            using (MemoryStream stream = new MemoryStream())
            {
                PdfReader reader = new PdfReader(bytes);
                using (PdfStamper stamper = new PdfStamper(reader, stream))
                {
                    int pages = reader.NumberOfPages;
                   for (int j = 2; j <= pages; j++)
                    {
                        ColumnText.ShowTextAligned(stamper.GetUnderContent(j), Element.ALIGN_RIGHT, new Phrase((j - 1).ToString(), blackFont), 568f, 15f, 0);
                    }
                }
                bytes = stream.ToArray();
            }
            System.IO.File.WriteAllBytes(@"D:\newPDF.pdf", bytes);
        }

Now, I need to create and add the Index with page numbers for this document. Here my problem is the index content also is dynamic data which will be some data in the document. While searching for my requirement, I found this,

int chapTemplateCounter = 0;
    public override void OnChapter(PdfWriter writer, Document document, float paragraphPosition, Paragraph title)
    {
        base.OnChapter(writer, document, paragraphPosition, title);

        BaseFont bfTimes = BaseFont.CreateFont(BaseFont.TIMES_ROMAN, BaseFont.CP1252, false);

        tableOfContentsTemplateList[chapTemplateCounter].BeginText();
        tableOfContentsTemplateList[chapTemplateCounter].SetFontAndSize(bfTimes, 12);
        tableOfContentsTemplateList[chapTemplateCounter].SetTextMatrix(0, 0);
        tableOfContentsTemplateList[chapTemplateCounter].ShowText("" + writer.PageNumber);
        tableOfContentsTemplateList[chapTemplateCounter].EndText();

        chapTemplateCounter++;
    }

I think it is useful for the static headers. How can I add index with page numbers in document with this code or Is it the correct way to generate PDF using Itextsharp

Thanks in Advance.

Saikiran
  • 1
  • 1
  • might this link helps you. http://stackoverflow.com/questions/3344060/generate-table-of-content-using-itextsharp – Chirag Sep 26 '16 at 11:34
  • Use can check this link, might be help you out. http://stackoverflow.com/questions/10515548/how-to-add-page-number-in-footer-in-pdf-by-itextsharp – Bharat Sep 26 '16 at 11:45
  • How exactly are the words to put into the index to be chosen? Shall there be an external list of words and you merely look for the occurrences of those words? Or shall the words to index somehow automatically be determined? – mkl Sep 26 '16 at 13:18
  • Looking at your code, it seems that you want to create a table of contents. I linked to a duplicate question in case you want to meet your requirement using iText 5. I would recommend you to upgrade to iText 7 though, and to take a look at the TOC examples in this chapter. http://developers.itextpdf.com/content/itext-7-building-blocks/chapter-6-creating-actions-destinations-and-bookmarks – Bruno Lowagie Sep 26 '16 at 13:33
  • @mkl : actually, the words are in index page coming from the Database which will be given by the users, We can't expect any thing. – Saikiran Sep 26 '16 at 13:34
  • @BrunoLowagie If I read Saikiran's comments correctly, he really tries to create an index, not a toc. – mkl Sep 26 '16 at 14:06
  • OK, I reopened the question. There's a class `IndexEvents` in iText 5 for this kind of work. I'm pretty sure I have an example somewhere. – Bruno Lowagie Sep 26 '16 at 14:34

1 Answers1

1

Please take a look at the IndexWords example.

In this example, we create an instance of the IndexEvents class, and we use that instance as a page event:

PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(dest));
IndexEvents index = new IndexEvents();
writer.setPageEvent(index);

Now when we add content to the document, we marks the words that we want to index like this:

Paragraph p = new Paragraph("Quick brown fox ");
p.add(index.create("jumps", "Jump"));
p.add(" over the lazy dog.");
document.add(p);

In this paragraph, we have marked the word "jumps" so that it is listed in the index as "Jump".

Or we mark words like this:

p = new Paragraph();
p.add(index.create("Quick brown fox", "Fox", "quick, brown"));
p.add(new Chunk(" jumps over "));
p.add(index.create("the lazy dog.", "Dog", "lazy"));
p.add(index.create(" ", "Jumping"));
document.add(p);

In this case, we have marked "Quick brown fox" with the keyword "Fox" and we have added a specification: "quick, brown". We have also added a keyword "Dog" and the specification "lazy". Finally, we also added a key word "Jumping".

Or we mark words like this:

p = new Paragraph();
p.add(new Chunk("The fox is "));
p.add(index.create("brown", "Color", "brown"));
p.add(index.create(" ", "Brown", "color", "see Color; brown"));
p.add(Chunk.NEWLINE);
document.add(p);

We mark "brown" as a "Color" and we specify "brown". We also add a reference. When people search or index for the word "Brown", we'll refer to "Color".

Once we have added all the content we need, we go to a new page, and we create the index:

document.newPage();
// we add the index
document.add(new Paragraph("Index:"));
List<Entry> list = index.getSortedEntries();
for (Entry entry : list) {
    Paragraph in = new Paragraph();
    in.add(new Chunk(entry.getIn1()));
    if (entry.getIn2().length() > 0) {
        in.add(new Chunk("; " + entry.getIn2()));
    }
    if (entry.getIn3().length() > 0) {
        in.add(new Chunk(" (" + entry.getIn3() + ")"));
    }
    List<Integer> pages = entry.getPagenumbers();
    List<String> tags = entry.getTags();
    in.add(": ");
    for (int i = 0, x = pages.size(); i < x; i++) {
        Chunk pagenr = new Chunk(" p" + pages.get(i));
        pagenr.setLocalGoto((String) tags.get(i));
        in.add(pagenr);
    }
    document.add(in);
}

You can check the result here: index_words.pdf

enter image description here

Bruno Lowagie
  • 75,994
  • 9
  • 109
  • 165