@iman.gharib
You can use setHyperlink(TextFragment textFragment) in order to set the link so that it would jump to specific text instead of complete page. However, when we tried to generate a PDF with such functionality of TOC, we faced an exception using following code:
java.util.List<TextFragment> tflist = new java.util.ArrayList<TextFragment>();
com.aspose.pdf.Document doc = new com.aspose.pdf.Document();
TextFragment tf = new TextFragment("Heading 1");
TextFragment tf2 = new TextFragment("Heading 2");
TextFragment tf3 = new TextFragment("Heading 3");
Page page = doc.getPages().add();
page.getParagraphs().add(tf);
page.getParagraphs().add(tf2);
page.getParagraphs().add(tf3);
tflist.add(tf);
tflist.add(tf2);
tflist.add(tf3);
doc.processParagraphs();
Page tocPage = doc.getPages().insert(1);
// Create object to represent TOC information
com.aspose.pdf.TocInfo tocInfo = new com.aspose.pdf.TocInfo();
com.aspose.pdf.TextFragment title = new com.aspose.pdf.TextFragment("Table Of Contents");
title.getTextState().setFontSize(20);
title.getTextState().setFontStyle(com.aspose.pdf.FontStyles.Bold);
// Set the title for TOC
tocInfo.setTitle(title);
tocPage.setTocInfo(tocInfo);
String[] titles = new String[4];
titles[0] = "Heading 1";
titles[1] = "Heading 2";
titles[2] = "Heading 3";
for (int i = 0; i < 3; i++) {
// Create Heading object
com.aspose.pdf.Heading heading2 = new com.aspose.pdf.Heading(1);
com.aspose.pdf.TextSegment segment2 = new com.aspose.pdf.TextSegment();
heading2.setTocPage(tocPage);
heading2.getSegments().add(segment2);
heading2.setHyperlink(new LocalHyperlink(tflist.get(i)));
// Destination coordinate
segment2.setText(titles[i]);
// Add heading to page containing TOC
tocPage.getParagraphs().add(heading2);
}
// Save the updated document
doc.save("TOC_Output_Java.pdf");
Therefore, we have logged an issue as PDFJAVA-39982 in our issue tracking system for further investigation on this case. We will look into its details and keep you posted with the status of its correction. Please be patient and spare us some time.
We are sorry for the inconvenience.