Search code examples
javaitext

iText PDF : How to create internal links to other sections in PDF


I'm using itext 5 to generate a pdf file and using Anchor to create internal links to different pages inside pdf. links are working fine but, In adobe PDF reader when mouse pointer is placed at the bottom edge of the link,'W' appears on top of Hand tool and when clicked it opens a new file in web browser but it is not redirecting to the linked page. Here is a sample code. Please suggest how to disable internal links opening in browser.

import com.itextpdf.text.Anchor;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.pdf.PdfWriter;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;


public class AnchorExample {

public static void main(String[] args) {

Document document = new Document();

try {
    PdfWriter.getInstance(document,
            new FileOutputStream("Anchor2.pdf"));

    document.open();


        Anchor anchor =
        new Anchor("Jump down to next paragraph");
        anchor.setReference("#linkTarget");
        Paragraph paragraph = new Paragraph();
        paragraph.add(anchor);
        document.add(paragraph);

        document.newPage();

        Anchor anchorTarget =
        new Anchor("This is the target of the link above");
        anchorTarget.setName("linkTarget");
        Paragraph targetParagraph = new Paragraph();
        targetParagraph.setSpacingBefore(50);

        targetParagraph.add(anchorTarget);
        document.add(targetParagraph);


    document.close();
} catch (DocumentException e) {
    e.printStackTrace();
} catch (FileNotFoundException e) {
    e.printStackTrace();
}

}
}

Solution

  • Using Anchor for internal links is something of the old days. I see that you're using an ancient version of iText, since the Anchor class (available up until iText 5) was replaced by the Link class (introduced in iText 7). See the overview of the iText 7 building block classes.

    Even in iText 5, it's not common to use Anchor for local destinations. It is better to use a Chunk instead of an Anchor, to use the setLocalDestination() method to define the target, and to use the setLocalGoto() method to define the link:

    Chunk chunk = new Chunk("Contact information");
    chunk.setLocalGoto("contact");  
    document.add(new Paragraph(chunk));
    document.newPage();
    chunk chunk1 = new Chunk("Contact information");
    chunk1.setLocalDestination("contact");
    Chapter chapter = new Chapter(new Paragraph(chunk1),1);    
    chapter.setNumberDepth(0);
    document.add(chapter);
    

    See also the almost duplicate question Add anchor to pdf using itext java. It's as if you copied your code from the question instead of from the answer (which is really strange).