Create Table of Contents (TOC) in PDF Using Java

Table of contents (TOC) makes the PDF documents more accessible and easier to navigate, especially for large files. In this article, you will learn how to create table of contents (TOC) in a PDF document using a free Java API.

Installation
Method 1: Download the free API (Free Spire.PDF for Java) and unzip it. Then add the Spire.Pdf.jar file to your project as dependency.

Method 2: You can also add the jar dependency to maven project by adding the following configurations to the pom.xml.

<repositories>
<repository>
<id>com.e-iceblue</id>
<name>e-iceblue</name>
<url>http://repo.e-iceblue.com/nexus/content/groups/public/</url>
</repository>
</repositories>
<dependencies>
<dependency>
<groupId>e-iceblue</groupId>
<artifactId>spire.pdf.free</artifactId>
<version>4.4.1</version>
</dependency>
</dependencies>

Sample Code

import com.spire.pdf.*;
import com.spire.pdf.actions.PdfGoToAction;
import com.spire.pdf.annotations.*;
import com.spire.pdf.general.PdfDestination;
import com.spire.pdf.graphics.*;
import java.awt.*;
import java.awt.geom.*;

public class TableOfContent {
public static void main(String[] args) throws Exception
{
//load PDF file
PdfDocument doc = new PdfDocument("input.pdf");
int pageCount = doc.getPages().getCount();
//Insert a new page as the first page to draw table of content
PdfPageBase tocPage = doc.getPages().insert(0);
//set title
String title = "Table Of Contents";
PdfTrueTypeFont titleFont = new PdfTrueTypeFont(new Font("Arial", Font.BOLD,20));
PdfStringFormat centerAlignment = new PdfStringFormat(PdfTextAlignment.Center, PdfVerticalAlignment.Middle);
Point2D location = new Point2D.Float((float) tocPage.getCanvas().getClientSize().getWidth() / 2, (float) titleFont.measureString(title).getHeight());
tocPage.getCanvas().drawString(title, titleFont, PdfBrushes.getCornflowerBlue(), location, centerAlignment);
//draw TOC text
PdfTrueTypeFont titlesFont = new PdfTrueTypeFont(new Font("Arial", Font.PLAIN,14));
String[] titles = new String[pageCount];
for (int i = 0; i < titles.length; i++) {
titles[i] = String.format("page%1$s", i + 1);
}
float y = (float)titleFont.measureString(title).getHeight() + 10;
float x = 0;
for (int i = 1; i <= pageCount; i++) {
String text = titles[i - 1];
Dimension2D titleSize = titlesFont.measureString(text);
PdfPageBase navigatedPage = doc.getPages().get(i);
String pageNumText = (String.valueOf(i+1));
Dimension2D pageNumTextSize = titlesFont.measureString(pageNumText);
tocPage.getCanvas().drawString(text, titlesFont, PdfBrushes.getCadetBlue(), 0, y);
float dotLocation = (float)titleSize.getWidth() + 2 + x;
float pageNumlocation = (float)(tocPage.getCanvas().getClientSize().getWidth() - pageNumTextSize.getWidth());
for (float j = dotLocation; j < pageNumlocation; j++) {
if (dotLocation >= pageNumlocation) {
break;
}
tocPage.getCanvas().drawString(".", titlesFont, PdfBrushes.getGray(), dotLocation, y);
dotLocation += 3;
}
tocPage.getCanvas().drawString(pageNumText, titlesFont, PdfBrushes.getCadetBlue(), pageNumlocation, y);
//add TOC action
Rectangle2D titleBounds = new Rectangle2D.Float(0,y,(float)tocPage.getCanvas().getClientSize().getWidth(),(float)titleSize.getHeight());
PdfDestination Dest = new PdfDestination(navigatedPage, new Point2D.Float(-doc.getPageSettings().getMargins().getTop(), -doc.getPageSettings().getMargins().getLeft()));
PdfActionAnnotation action = new PdfActionAnnotation(titleBounds, new PdfGoToAction(Dest));
action.setBorder(new PdfAnnotationBorder(0));
((PdfNewPage) ((tocPage instanceof PdfNewPage) ? tocPage : null)).getAnnotations().add(action);
y += titleSize.getHeight() + 10;
}

//save the resultant file
doc.saveToFile("addTableOfContent.pdf");
doc.close();
}
}

--

--

Sharing Java Code

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store