Free Support Forum - aspose.com

Create TOC Java PDF

Hi all,
considering the sample PDF I have added, is it posible to create such a PDF using java pdf?
The exampe provided in git jumps only to the page. I need to jump to specific Header. The Headers might have the same text.

regards, Iman

Inhalt.pdf (67.1 KB)

@iman.gharib

Do you want to generate similar output from scratch? OR do you want to add TOC in an existing PDF document? Please share the requested information so that we can provide our feedback accordingly.

Hi Ali,
I am creating from the scratch.

regards
Iman

@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.