How to Add PDF Bookmarks and Outline in Java

This article was translated from English: Does it need improvement?
Translated
View the article in English

Including PDF bookmarks in your Java project can significantly improve the usability and navigation of your PDFs. Outlines in PDFs provide an easy method of navigation within the PDF itself, so you can easily navigate to key pages within the document much like how you would with a table of contents.

IronPDF is a powerful PDF tool that makes working with PDF files a breeze. Its bookmarking tool gives you a concise, easy-to-use method for creating custom bookmarks for your PDF files.

Comience a usar IronPDF en su proyecto hoy con una prueba gratuita.

Primer Paso:
green arrow pointer

Before We Get Started

You will also need to make sure you have your license key set up correctly, as IronPDF must be licensed for development.

Add Outline & Bookmarks Example

For today's example, I will use this sample PDF to apply the outline and bookmarks.

Add Single Layer of Bookmarks

After loading this PDF from the specified file path using the PdfDocument class, we can start adding bookmarks to the document by retrieving the BookmarkManager object. You can add the bookmark to the start or end of the bookmark collection using the addBookMarkAtEnd and addBookMarkAtStart methods.

ConsejosRemember that all page indexes follow zero-based indexing.

import java.io.IOException;
import java.nio.file.Path;
import com.ironsoftware.ironpdf.PdfDocument;
import com.ironsoftware.ironpdf.bookmark.BookmarkManager;

public class Main {
    public static void main(String[] args) throws IOException {
        // Set the license key for IronPDF
        License.setLicenseKey("IRONPDF-MYLICENSE-KEY-1EF01");

        // Load the PDF file
        PdfDocument pdf = PdfDocument.fromFile(Path.of("NovelSample.pdf"));

        // Get BookmarkManager object to manage bookmarks
        BookmarkManager bookmarks = pdf.getBookmark();

        // Add bookmarks at the end of the bookmark collection
        bookmarks.addBookMarkAtEnd("Title Page", 0);
        bookmarks.addBookMarkAtEnd("Table of Contents", 1);
        bookmarks.addBookMarkAtEnd("Dedication Page", 2);
        bookmarks.addBookMarkAtEnd("First Page", 3);
        bookmarks.addBookMarkAtStart("Page 4", 6);

        // Save the modified PDF with bookmarks
        pdf.saveAs(Path.of("bookmarked.pdf"));
    }
}
import java.io.IOException;
import java.nio.file.Path;
import com.ironsoftware.ironpdf.PdfDocument;
import com.ironsoftware.ironpdf.bookmark.BookmarkManager;

public class Main {
    public static void main(String[] args) throws IOException {
        // Set the license key for IronPDF
        License.setLicenseKey("IRONPDF-MYLICENSE-KEY-1EF01");

        // Load the PDF file
        PdfDocument pdf = PdfDocument.fromFile(Path.of("NovelSample.pdf"));

        // Get BookmarkManager object to manage bookmarks
        BookmarkManager bookmarks = pdf.getBookmark();

        // Add bookmarks at the end of the bookmark collection
        bookmarks.addBookMarkAtEnd("Title Page", 0);
        bookmarks.addBookMarkAtEnd("Table of Contents", 1);
        bookmarks.addBookMarkAtEnd("Dedication Page", 2);
        bookmarks.addBookMarkAtEnd("First Page", 3);
        bookmarks.addBookMarkAtStart("Page 4", 6);

        // Save the modified PDF with bookmarks
        pdf.saveAs(Path.of("bookmarked.pdf"));
    }
}
JAVA

With the PDF viewer above, you can check the table of contents, which is located at the top left corner of most browsers, to see all the bookmarks that we have added.

Add Multiple Layers of Bookmarks

In this example, we'll start by adding bookmarks, just like we did when creating a single layer of bookmarks. Next, we'll use the insertBookmark method to add a new bookmark on a new layer and give it a name using the method's first parameter. The second parameter specifies the page the new bookmark links to. To create a new layer, we make the new bookmark a "child" of an existing bookmark, which is done using the method's third parameter.

import java.io.IOException;
import java.nio.file.Path;
import com.ironsoftware.ironpdf.PdfDocument;
import com.ironsoftware.ironpdf.bookmark.BookmarkManager;

public class Main {
    public static void main(String[] args) throws IOException {
        // Load the PDF file
        PdfDocument pdf = PdfDocument.fromFile(Path.of("NovelSample.pdf"));

        // Get BookmarkManager object
        BookmarkManager bookmarks = pdf.getBookmark();

        // Add bookmarks at the end
        bookmarks.addBookMarkAtEnd("Title Page", 0);
        bookmarks.addBookMarkAtEnd("Table of Contents", 1);
        bookmarks.addBookMarkAtEnd("Dedication", 2);

        // Insert second layer bookmarks
        bookmarks.insertBookmark("First Page", 3, "Table of Contents", null);
        bookmarks.insertBookmark("Second Page", 4, "Table of Contents", "First Page");
        bookmarks.insertBookmark("End of Sample", 7, "Title Page", null);
        bookmarks.insertBookmark("Fourth page", 6, "Table of Contents", "Second Page");

        // Save the modified PDF with multiple layer bookmarks
        pdf.saveAs(Path.of("multiLayer.pdf"));
    }
}
import java.io.IOException;
import java.nio.file.Path;
import com.ironsoftware.ironpdf.PdfDocument;
import com.ironsoftware.ironpdf.bookmark.BookmarkManager;

public class Main {
    public static void main(String[] args) throws IOException {
        // Load the PDF file
        PdfDocument pdf = PdfDocument.fromFile(Path.of("NovelSample.pdf"));

        // Get BookmarkManager object
        BookmarkManager bookmarks = pdf.getBookmark();

        // Add bookmarks at the end
        bookmarks.addBookMarkAtEnd("Title Page", 0);
        bookmarks.addBookMarkAtEnd("Table of Contents", 1);
        bookmarks.addBookMarkAtEnd("Dedication", 2);

        // Insert second layer bookmarks
        bookmarks.insertBookmark("First Page", 3, "Table of Contents", null);
        bookmarks.insertBookmark("Second Page", 4, "Table of Contents", "First Page");
        bookmarks.insertBookmark("End of Sample", 7, "Title Page", null);
        bookmarks.insertBookmark("Fourth page", 6, "Table of Contents", "Second Page");

        // Save the modified PDF with multiple layer bookmarks
        pdf.saveAs(Path.of("multiLayer.pdf"));
    }
}
JAVA

Here you can see the PDF with our new tree structure of bookmarks. Check out the outline for yourself to see how the insertBookmark feature has added a new layer of bookmarks.


Retrieving Bookmarks

IronPDF's bookmarking tool not only adds new bookmarks but also retrieves and views existing ones. To navigate through bookmarks, first load the PDF using the PdfDocument.fromFile method. Then, access the BookmarkManager object and use the getBookmarks method to retrieve all bookmarks, including child bookmarks. Finally, use the get method to retrieve a bookmark by its index in the list.

import java.io.IOException;
import java.nio.file.Path;
import java.util.List;
import com.ironsoftware.ironpdf.License;
import com.ironsoftware.ironpdf.PdfDocument;
import com.ironsoftware.ironpdf.bookmark.Bookmark;
import com.ironsoftware.ironpdf.bookmark.BookmarkManager;

public class Main {
    public static void main(String[] args) throws IOException {
        // Load the PDF file with bookmarks
        PdfDocument pdf = PdfDocument.fromFile(Path.of("bookmarked.pdf"));

        // Retrieve the bookmark manager
        BookmarkManager bookmarks = pdf.getBookmark();

        // Retrieve list of all bookmarks
        List<Bookmark> bookmarkList = bookmarks.getBookmarks();

        // Retrieve a specific bookmark by its index
        Bookmark bookmark = bookmarkList.get(2);

        // Example usage of the retrieved bookmark could be added here
    }
}
import java.io.IOException;
import java.nio.file.Path;
import java.util.List;
import com.ironsoftware.ironpdf.License;
import com.ironsoftware.ironpdf.PdfDocument;
import com.ironsoftware.ironpdf.bookmark.Bookmark;
import com.ironsoftware.ironpdf.bookmark.BookmarkManager;

public class Main {
    public static void main(String[] args) throws IOException {
        // Load the PDF file with bookmarks
        PdfDocument pdf = PdfDocument.fromFile(Path.of("bookmarked.pdf"));

        // Retrieve the bookmark manager
        BookmarkManager bookmarks = pdf.getBookmark();

        // Retrieve list of all bookmarks
        List<Bookmark> bookmarkList = bookmarks.getBookmarks();

        // Retrieve a specific bookmark by its index
        Bookmark bookmark = bookmarkList.get(2);

        // Example usage of the retrieved bookmark could be added here
    }
}
JAVA

Insert Bookmark at Specific Index

With the retrieved bookmarks, you have the option to add new bookmarks at specific indexes within the document. To do this, select the targeted bookmark and use the addNextBookmark method to add a new bookmark after it. For example, we take the PDF from the 'Add Multiple Layers of Bookmarks' section and add a bookmark after the 'Third Page' bookmark. You can also add a child bookmark as a deeper layer using the addChildBookmark method.

import java.io.IOException;
import java.nio.file.Path;
import java.util.List;
import com.ironsoftware.ironpdf.PdfDocument;
import com.ironsoftware.ironpdf.bookmark.Bookmark;
import com.ironsoftware.ironpdf.bookmark.BookmarkManager;

public class Main {
    public static void main(String[] args) throws IOException {
        // Load the PDF we modified earlier
        PdfDocument pdf = PdfDocument.fromFile(Path.of("multiLayer.pdf"));

        // Get the BookmarkManager
        BookmarkManager bookmarks = pdf.getBookmark();

        // Retrieve the list of bookmarks
        List<Bookmark> bookmarkList = bookmarks.getBookmarks();

        // Retrieve a specific bookmark by its index
        Bookmark bookmark = bookmarkList.get(5);

        // Add a new bookmark after the specified bookmark
        bookmark.addNextBookmark("Fourth Page", 6);

        // Add another layer to 'Third page' bookmark
        bookmark.addChildBookmark("Section 1", 7);

        // Save the modified PDF
        pdf.saveAs(Path.of("specificIndex.pdf"));
    }
}
import java.io.IOException;
import java.nio.file.Path;
import java.util.List;
import com.ironsoftware.ironpdf.PdfDocument;
import com.ironsoftware.ironpdf.bookmark.Bookmark;
import com.ironsoftware.ironpdf.bookmark.BookmarkManager;

public class Main {
    public static void main(String[] args) throws IOException {
        // Load the PDF we modified earlier
        PdfDocument pdf = PdfDocument.fromFile(Path.of("multiLayer.pdf"));

        // Get the BookmarkManager
        BookmarkManager bookmarks = pdf.getBookmark();

        // Retrieve the list of bookmarks
        List<Bookmark> bookmarkList = bookmarks.getBookmarks();

        // Retrieve a specific bookmark by its index
        Bookmark bookmark = bookmarkList.get(5);

        // Add a new bookmark after the specified bookmark
        bookmark.addNextBookmark("Fourth Page", 6);

        // Add another layer to 'Third page' bookmark
        bookmark.addChildBookmark("Section 1", 7);

        // Save the modified PDF
        pdf.saveAs(Path.of("specificIndex.pdf"));
    }
}
JAVA

Por favor notaIf you merge two PDF documents together whose bookmarks share identical names, this can lead to a disruption in the bookmark list itself.

Preguntas Frecuentes

¿Cómo puedo agregar marcadores a un PDF en Java?

Para agregar marcadores a un PDF en Java, utiliza la biblioteca IronPDF. Carga tu PDF usando la clase PdfDocument, y luego utiliza la clase BookmarkManager para insertar y personalizar marcadores. Finalmente, guarda el documento para aplicar los cambios.

¿Cuáles son los beneficios de usar marcadores en documentos PDF?

Los marcadores en documentos PDF mejoran enormemente la navegación y usabilidad al permitir que los usuarios salten directamente a secciones importantes, similar a una tabla de contenidos.

¿Cómo creo marcadores jerárquicos en un PDF usando Java?

Para crear marcadores jerárquicos en un PDF usando Java, utiliza la clase BookmarkManager de IronPDF. Usa el método insertBookmark para agregar marcadores hijos bajo marcadores existentes, creando así múltiples capas.

¿Cuál es el método recomendado para configurar la licencia de IronPDF en Java?

Configura tu licencia de IronPDF en Java llamando al método License.setLicenseKey con tu clave de licencia antes de usar cualquier característica de PDF para asegurar plena funcionalidad.

¿Puede IronPDF manejar la recuperación de marcadores PDF existentes?

Sí, IronPDF puede recuperar marcadores PDF existentes. Carga el PDF con la clase PdfDocument, accede al BookmarkManager, y usa el método getBookmarks para listar todos los marcadores.

¿Cómo puedo agregar un marcador a una página específica en un PDF usando Java?

En Java, usa el método addBookMarkAtEnd de IronPDF para agregar un marcador a una página específica dentro de un documento PDF. Esto te permite señalar y resaltar secciones clave.

¿Cuál es la importancia de la indexación basada en cero al trabajar con marcadores de PDF?

La indexación basada en cero es crucial al trabajar con marcadores de PDF porque los números de página empiezan en cero. Por ejemplo, la primera página es el índice 0, lo cual es esencial para una correcta colocación de marcadores.

¿Cómo guardo un PDF modificado con nuevos marcadores usando IronPDF en Java?

Después de agregar o modificar marcadores en un PDF usando IronPDF, guarda el documento actualizado usando el método saveAs de la clase PdfDocument para mantener tus cambios.

¿Qué debo considerar al combinar PDFs con marcadores usando IronPDF?

Al combinar PDFs con marcadores usando IronPDF, asegúrate de que los marcadores tengan nombres únicos para mantener una lista de marcadores coherente y organizada sin conflictos.

¿Cómo puedo agregar un marcador hijo en un PDF usando IronPDF?

Para agregar un marcador hijo en un PDF usando IronPDF, emplea el método addChildBookmark, que te permite construir una estructura de marcadores jerárquica más profunda dentro del documento.

¿IronPDF es compatible con .NET 10 para marcadores y esquemas?

Sí. IronPDF es compatible con .NET 10. Como se muestra en los metadatos de su paquete NuGet, versiones como la 2023.6.10 se calculan para net10.0 junto con los destinos Android, iOS, navegadores, MacCatalyst, macOS, tvOS y Windows, lo que permite la funcionalidad completa de marcadores y esquemas en .NET 10. ([nuget.org](https://www.nuget.org/packages/IronPdf/2023.6.10?utm_source=openai))

Darrius Serrant
Ingeniero de Software Full Stack (WebOps)

Darrius Serrant tiene una licenciatura en Ciencias de la Computación de la Universidad de Miami y trabaja como Ingeniero de Marketing WebOps Full Stack en Iron Software. Atraído por la programación desde joven, vio la computación como algo misterioso y accesible, convirtiéndolo en el ...

Leer más
¿Listo para empezar?
Versión: 2025.11 recién lanzado