Gopi Lal
Gopi Lal

Reputation: 427

How to give a bookmark for a text in PDF IText 5?

I know it may sound simple...but I have been searching for the code for adding bookmark, when the bookmark is clicked should go to the text content which is there in PDF.

Lets say I have bookmark GO TO XYZ and in the PDF I have added doc.add(new Phrase("Should Point Me"))

Here is my code

PdfOutline root = writer.getRootOutline();
PdfOutline gotoXyz= new PdfOutline(root,
                    new PdfDestination(PdfDestination.FITH, writer.getVerticalPosition(true)), "GO TO XYZ", true);

I found in Itext 7 we give ExplicitDestination with pageNumber...neither I can use Itext7 or use pageNumber I need to point to text content in PDF using bookmark...

Please help me on this..

Upvotes: 0

Views: 1072

Answers (1)

Bruno Lowagie
Bruno Lowagie

Reputation: 77528

PART 1

You have:

doc.add(new Phrase("Should Point Me"));

Replace this with:

Paragraph p = new Paragraph("This is the ");
Chunk chunk = new Chunk("destination");
chunk.setLocalDestination("XYZ");
p.add(chunk);
doc.add(p);

You have now create a local destination with name XYZ. This is similar to having <a name="XYZ"> in HTML.

PART 2

You now need something like <a href="#XYZ">. That would be an action:

PdfAction action = PdfAction.gotoLocalPage("XYZ", false);

You can use this action from your content like this:

Paragraph p = new Paragraph("Go to ");
Chunk destination = new Chunk("destination");
destination.setAction(PdfAction.gotoLocalPage("XYZ", false));
p.add(destination);
document.add(p);

You can also use this action in the context of a PdfOutline.

You have:

PdfOutline root = writer.getRootOutline();
PdfOutline gotoXyz= new PdfOutline(root,
    new PdfDestination(PdfDestination.FITH, writer.getVerticalPosition(true)), "GO TO XYZ", true);

And that might work approximately, but this should also work:

PdfOutline root = writer.getRootOutline();
PdfOutline gotoXyz= new PdfOutline(root,
    new PdfDestination("XYZ"), "GO TO XYZ");

You probably could even use this:

PdfOutline root = writer.getRootOutline();
PdfOutline gotoXyz= new PdfOutline(root,
    PdfAction.gotoLocalPage("XYZ", false), "GO TO XYZ");

Upvotes: 1

Related Questions