Skip to main content

Add Table of Contents (TOC) to PDF in Java


Adding table of contents (TOC) to our document is a useful way to show readers what chapters are included in our document. When readers click on the table of contents, they can quickly navigate to the specific parts that they’re interested.

In this blog, I will introduce how to add table of contents (TOC) to a PDF document programmatically in Java using Free Spire.PDF for Java library.


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 document
       
PdfDocument doc = new PdfDocument("sample.pdf");
       
int pageCount = doc.getPages().getCount();
       
//Insert a page as the first page to draw TOC
       
PdfPageBase tocPage = doc.getPages().insert(0);
       
//set TOC 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 content and set font, style and location
       
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 action to TOC in order to link it to corresponding location in the file
           
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 document
       
doc.saveToFile("addTableOfContent.pdf");
        doc.close();
    }
}

Output:



Comments

Popular posts from this blog

3 Ways to Generate Word Documents from Templates in Java

A template is a document with pre-applied formatting like styles, tabs, line spacing and so on. You can quickly generate a batch of documents with the same structure based on the template. In this article, I am going to show you the different ways to generate Word documents from templates programmatically in Java using Free Spire.Doc for Java library. Prerequisite First of all, you need to add needed dependencies for including Free Spire.Doc for Java into your Java project. There are two ways to do that. If you use maven, you need to add the following code to your project’s pom.xml file. <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>               <g

Simple Java Code to Convert Excel to PDF in Java

This article demonstrates a simple solution to convert an Excel file to PDF in Java by using free Excel API – Free Spire.XLS for Java . The following examples illustrate two possibilities to convert Excel to PDF:      Convert the whole Excel file to PDF     Convert a particular Excel Worksheet to PDF Before start with coding, you need to Download Free Spire.XLS for Java package , unzip it and import Spire.Xls.jar file from the lib folder in your project as a denpendency. 1. Convert the whole Excel file to PDF Spire.XLS for Java provides saveToFile method in Workbook class that enables us to easily save a whole Excel file to PDF. import com.spire.xls.FileFormat; import com.spire.xls.Workbook; public class ExcelToPDF {     public static void main(String[] args){         //Create a Workbook         Workbook workbook = new Workbook();         workbook.loadFromFile( "Sample.xlsx" );         //Fit to page         workbook.getConverterSetting().setShee

Insert and Extract OLE objects in Word in Java

You can use OLE (Object Linking and Embedding) to include content from other programs, such as another Word document, an Excel or PowerPoint document to an existing Word document. This article demonstrates how to insert and extract embedded OLE objects in a Word document in Java by using Free Spire.Doc for Java API.   Add dependencies First of all, you need to add needed dependencies for including Free Spire.Doc for Java into your Java project. There are two ways to do that. If you use maven, you need to add the following code to your project’s pom.xml file.     <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>