Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iText having issues with Anchors (clickable but nothing happens)

Tags:

java

itext

I'm trying to create a simple table of contents (the document is only 4 pages long). The issue I have is that while my mouse does turn into a hand, when I click it nothing happens. And yes the targets are on another page.

creation of a table of contents line:

Chunk chunk = new Chunk("Contact information");
chunk.setLocalGoto("Contact information");  
document.add(new Paragraph(chunk));

One of the targets:

Anchor anchor = new Anchor("Contact information", font1);
anchor.setName("Contact information");
Chapter chapter = new Chapter(new Paragraph(anchor), 1);    
chapter.setNumberDepth(0);
document.add(chapter);

The Goto String matches with the Anchor name so I don't see what I'm doing wrong.

like image 459
jack Avatar asked Jan 04 '11 09:01

jack


1 Answers

In this example from iText in Action, the internal link uses a # in the name.

Another approach would be to use Chunks for both the link and the destination.

chunkDest.setLocalDesitination("foo");
...
chunkLink.setLocalGoto("foo"); // or "#foo"?

My reading of PdfDocument (localGoto and localDestination) leads me to believe that the order in which they're created doesn't matter... wait... Nope, shouldn't matter so long as both are actually called.

Have you actually stepped through your code to be sure they're both Actually Called?

Another option: End run. Drop down to the PDF-native code and do it there. Build your own PdfDestination for the chapter location and PdfAction for the TOC. Something like this:

PdfDestination fitH = new PdfDestination(PdfDestination.FITH);
// the destination doesn't have a page associated with it until you call
//  gotoLocalPage.  Kinda goofy, but we can work with it.
PdfAction link = PdfAction.gotoLocalPage(pageNum, fitH, writer);
chunk.setAction(link);

NOTES:

  1. You can reuse a given PdfAction if you need multiple links to the same spot.
  2. There are many ways to define a PdfDestination, I just used the one I prefer. YMMV.
like image 172
Mark Storer Avatar answered Oct 22 '22 05:10

Mark Storer