Incorporating Bookmarks in C# and .NET

Bookmarks are an essential feature in PDF documents, providing a convenient way to navigate through the content. They enhance the user experience by allowing quick access to specific sections of a document. In this article, we will explore how to incorporate bookmarks in PDF documents using C# and .NET, leveraging the capabilities of the SautinSoft PDF.Net library.

Here are a few ways bookmarks can help in the user experience:

  • Fast navigation. Bookmarks allow users to quickly navigate to the desired sections of a document without scrolling through it manually. This is especially useful in long documents such as books, reports, or technical manuals.
  • Content organization. Bookmarks help to structure a document, making it more organized and easy to read. Users can see the table of contents and quickly find the sections they are interested in.
  • Increase productivity. With bookmarks, users can find the information they need faster, which saves time and increases productivity. This is especially important for professionals working with large amounts of data.
  • Improving the user experience. Bookmarks make the interaction with the document more intuitive and convenient. Users can easily return to important sections, which improves the overall experience of working with the document.
  • Support for a multi-level structure. Bookmarks can support a multi-level structure, which allows users to see the hierarchy of sections and subsections. This helps to better understand the structure of the document and find the necessary information.
  • Compatible with various devices. Bookmarks work on a variety of devices and platforms, making them a versatile tool for navigation. Users can easily use bookmarks on computers, tablets and smartphones.
  • Search support. In some cases, bookmarks can be integrated with the search function, which allows users to find the desired sections by keywords or phrases.
  • Step-by-step guide:

  1. Add SautinSoft.PDF from NuGet.
  2. Create a new PDF document.
  3. Get the number of pages.
  4. Add a new outline item (bookmark) at the end of the document outline collection.
  5. Save the document.

Output result:

Полный код

using System;
using SautinSoft.Pdf;
using System.IO;

class Program
{
    /// <summary>
    /// Bookmarks.
    /// </summary>
    /// <remarks>
    /// Details: https://sautinsoft.com/products/pdf/help/net/developer-guide/bookmarks.php
    /// </remarks>
    static void Main()
    {
        // Before starting this example, please get a free 100-day trial key:
        // https://sautinsoft.com/start-for-free/

        // Apply the key here:
        // PdfDocument.SetLicense("...");

        using (var document = new PdfDocument())
        {
            document.Pages.Add();
            // Remove all bookmarks.
            document.Outlines.Clear();
            // Get the number of pages.
            int numberOfPages = document.Pages.Count;
            for (int i = 0; i < numberOfPages; i += 10)
            {
                // Add a new outline item (bookmark) at the end of the document outline collection.
                var bookmark = document.Outlines.AddLast(string.Format("PAGES {0}-{1}", i + 1, Math.Min(i + 10, numberOfPages)));
                // Set the explicit destination on the new outline item (bookmark).
                bookmark.SetDestination(document.Pages[i], PdfDestinationViewType.FitRectangle, 0, 0, 100, 100);
                for (int j = 0; j < Math.Min(10, numberOfPages - i); j++)
                    // Add a new outline item (bookmark) at the end of parent outline item (bookmark) and set the explicit destination.
                    bookmark.Outlines.AddLast(string.Format("PAGE {0}", i + j + 1)).SetDestination(document.Pages[i + j], PdfDestinationViewType.FitPage);
            }
            document.PageMode = PdfPageMode.UseOutlines;
            document.Save("Bookmarks.pdf");
        }

        System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo("Bookmarks.pdf") { UseShellExecute = true });
    }
}

Download

Option Infer On

Imports System
Imports SautinSoft.Pdf
Imports System.IO

Friend Class Program
	''' <summary>
	''' Bookmarks.
	''' </summary>
	''' <remarks>
	''' Details: https://sautinsoft.com/products/pdf/help/net/developer-guide/bookmarks.php
	''' </remarks>
	Shared Sub Main()
		' Before starting this example, please get a free 100-day trial key:
		' https://sautinsoft.com/start-for-free/

		' Apply the key here:
		' PdfDocument.SetLicense("...");

		Using document = New PdfDocument()
			document.Pages.Add()
			' Remove all bookmarks.
			document.Outlines.Clear()
			' Get the number of pages.
			Dim numberOfPages As Integer = document.Pages.Count
			Dim i As Integer = 0
			Do While i < numberOfPages
				' Add a new outline item (bookmark) at the end of the document outline collection.
				Dim bookmark = document.Outlines.AddLast(String.Format("PAGES {0}-{1}", i + 1, Math.Min(i + 10, numberOfPages)))
				' Set the explicit destination on the new outline item (bookmark).
				bookmark.SetDestination(document.Pages(i), PdfDestinationViewType.FitRectangle, 0, 0, 100, 100)
				Dim j As Integer = 0
				Do While j < Math.Min(10, numberOfPages - i)
					' Add a new outline item (bookmark) at the end of parent outline item (bookmark) and set the explicit destination.
					bookmark.Outlines.AddLast(String.Format("PAGE {0}", i + j + 1)).SetDestination(document.Pages(i + j), PdfDestinationViewType.FitPage)
					j += 1
				Loop
				i += 10
			Loop
			document.PageMode = PdfPageMode.UseOutlines
			document.Save("Bookmarks.pdf")
		End Using

		System.Diagnostics.Process.Start(New System.Diagnostics.ProcessStartInfo("Bookmarks.pdf") With {.UseShellExecute = True})
	End Sub
End Class

Download


Если вам нужен пример кода или у вас есть вопрос: напишите нам по адресу support@sautinsoft.ru или спросите в онлайн-чате (правый нижний угол этой страницы) или используйте форму ниже:



Вопросы и предложения всегда приветствуются!

Мы разрабатываем компоненты .Net с 2002 года. Мы знаем форматы PDF, DOCX, RTF, HTML, XLSX и Images. Если вам нужна помощь в создании, изменении или преобразовании документов в различных форматах, мы можем вам помочь. Мы напишем для вас любой пример кода абсолютно бесплатно.