VintaSoft Imaging .NET SDK 15.1: Документация для .NET разработчика
В этом разделе
PDF: Навигация по PDF документу
В этом разделе

PDF закладки

PDF документ может содержать оглавление. Оглавление может отображаться таким образом, чтобы предоставить пользователю возможность перемещаться по документу с помощью мыши и клавиатуры. Оглавление имеет древовидную структуру и называется Закладками.

Группа закладок определяется с помощью класса PdfBookmarkCollection. Одиночная закладка определяется с помощью класса PdfBookmark.


Получение закладок в виде древовидной структуры

Закладки документа можно получить с помощью свойства PdfDocument.Bookmarks.

Вот код на C#/VB.NET, который демонстрирует, как отобразить информацию о дереве закладок в PDF-документе:
/// <summary>
/// Prints information about the bookmark collection of specified PDF document.
/// </summary>
/// <param name="filename">The filename of PDF document.</param>
public static void PrintBookmarks(string filename)
{
    // open PDF document in read-only mode
    Vintasoft.Imaging.Pdf.PdfDocument document = 
        new Vintasoft.Imaging.Pdf.PdfDocument(filename, true);

    // print Bookrmarks collection
    PrintBookmarkCollection(document.Bookmarks, "");

    // close document
    document.Dispose();
}

/// <summary>
/// Prints information about the bookmark collection of PDF document.
/// </summary>
public static void PrintBookmarkCollection(
    Vintasoft.Imaging.Pdf.Tree.PdfBookmarkCollection bookmarks, string indent)
{
    // for each bookmarks in the collection
    for (int i = 0; i < bookmarks.Count; i++)
    {
        Vintasoft.Imaging.Pdf.Tree.PdfBookmark bookmark = bookmarks[i];

        // print indent
        System.Console.Write(indent);

        // print status of child bookmarks
        System.Console.Write(bookmark.ChildBookmarks.Count > 0 ? "+" : "-");

        // print title
        System.Console.Write(bookmark.Title);

        // find destination page
        Vintasoft.Imaging.Pdf.Tree.PdfDestinationBase destination = bookmark.Destination;
        if (destination == null)
        {
            if (bookmark.Action != null && 
                bookmark.Action is Vintasoft.Imaging.Pdf.Tree.PdfGotoAction)
            {
                destination = ((Vintasoft.Imaging.Pdf.Tree.PdfGotoAction)bookmark.Action).Destination;
            }
        }
        if (destination != null)
        {
            // print destination page number
            int pageIndex = bookmark.Document.Pages.IndexOf(destination.Page);
            System.Console.Write(": Page " + (pageIndex + 1).ToString());
        }

        // print bookmark Flags
        if (bookmark.Flags != Vintasoft.Imaging.Pdf.Tree.PdfBookmarkFlags.None)
            System.Console.Write(" (" + bookmark.Flags + ")");
        System.Console.WriteLine();

        // print child bookmarks
        PrintBookmarkCollection(bookmark.ChildBookmarks, indent + "  ");
    }
}
''' <summary>
''' Prints information about the bookmark collection of specified PDF document.
''' </summary>
''' <param name="filename">The filename of PDF document.</param>
Public Shared Sub PrintBookmarks(filename As String)
    ' open PDF document in read-only mode
    Dim document As New Vintasoft.Imaging.Pdf.PdfDocument(filename, True)

    ' print Bookrmarks collection
    PrintBookmarkCollection(document.Bookmarks, "")

    ' close document
    document.Dispose()
End Sub

''' <summary>
''' Prints information about the bookmark collection of PDF document.
''' </summary>
Public Shared Sub PrintBookmarkCollection(bookmarks As Vintasoft.Imaging.Pdf.Tree.PdfBookmarkCollection, indent As String)
    ' for each bookmarks in the collection
    For i As Integer = 0 To bookmarks.Count - 1
        Dim bookmark As Vintasoft.Imaging.Pdf.Tree.PdfBookmark = bookmarks(i)

        ' print indent
        System.Console.Write(indent)

        ' print status of child bookmarks
        System.Console.Write(If(bookmark.ChildBookmarks.Count > 0, "+", "-"))

        ' print title
        System.Console.Write(bookmark.Title)

        ' find destination page
        Dim destination As Vintasoft.Imaging.Pdf.Tree.PdfDestinationBase = bookmark.Destination
        If destination Is Nothing Then
            If bookmark.Action IsNot Nothing AndAlso TypeOf bookmark.Action Is Vintasoft.Imaging.Pdf.Tree.PdfGotoAction Then
                destination = DirectCast(bookmark.Action, Vintasoft.Imaging.Pdf.Tree.PdfGotoAction).Destination
            End If
        End If
        If destination IsNot Nothing Then
            ' print destination page number
            Dim pageIndex As Integer = bookmark.Document.Pages.IndexOf(destination.Page)
            System.Console.Write(": Page " & (pageIndex + 1).ToString())
        End If

        ' print bookmark Flags
        If bookmark.Flags <> Vintasoft.Imaging.Pdf.Tree.PdfBookmarkFlags.None Then
            System.Console.Write(" (" & Convert.ToString(bookmark.Flags) & ")")
        End If
        System.Console.WriteLine()

        ' print child bookmarks
        PrintBookmarkCollection(bookmark.ChildBookmarks, indent & "  ")
    Next
End Sub


Добавление новой закладки

Чтобы добавить закладку, необходимо сделать следующее:
Вот код на C#/VB.NET, который демонстрирует, как добавлять новые закладки в PDF-документ:
/// <summary>
/// Creates bookmarks in PDF document.
/// </summary>
/// <param name="pdfFilename">The filename of PDF document.</param>
public static void CreateBookmarks(string pdfFilename)
{
    // open PDF document in read-write mode
    Vintasoft.Imaging.Pdf.PdfDocument document = 
        new Vintasoft.Imaging.Pdf.PdfDocument(pdfFilename);

    // if PDF document does not contain bookmark collection
    if (document.Bookmarks == null)
        // create bookmark collection of PDF document
        document.Bookmarks = 
            new Vintasoft.Imaging.Pdf.Tree.PdfBookmarkCollection(document);

    // get bookmarks collection
    Vintasoft.Imaging.Pdf.Tree.PdfBookmarkCollection bookmarks = document.Bookmarks;

    if (bookmarks.Count > 1)
    {
        // delete first bookmark
        bookmarks.RemoveAt(0);
        // delete last bookmark
        bookmarks.RemoveAt(bookmarks.Count - 1);
    }

    // create first bookmark
    Vintasoft.Imaging.Pdf.Tree.PdfBookmark firstBookmark = 
        new Vintasoft.Imaging.Pdf.Tree.PdfBookmark(document);
    firstBookmark.Title = "First Page";
    firstBookmark.Flags = Vintasoft.Imaging.Pdf.Tree.PdfBookmarkFlags.Bold;
    firstBookmark.Destination = new Vintasoft.Imaging.Pdf.Tree.PdfDestinationFit(document, document.Pages[0]);

    // create last bookmark
    Vintasoft.Imaging.Pdf.Tree.PdfBookmark lastBookmark = 
        new Vintasoft.Imaging.Pdf.Tree.PdfBookmark(document);
    lastBookmark.Title = "Last Page";
    lastBookmark.Flags = Vintasoft.Imaging.Pdf.Tree.PdfBookmarkFlags.Bold;
    lastBookmark.Destination = 
        new Vintasoft.Imaging.Pdf.Tree.PdfDestinationFit(document, document.Pages[document.Pages.Count - 1]);

    // insert first bookmark
    bookmarks.Insert(0, firstBookmark);

    // add last bookmark
    bookmarks.Add(lastBookmark);

    // save document
    document.SaveChanges();

    // close document
    document.Dispose();
}
''' <summary>
''' Creates bookmarks in PDF document.
''' </summary>
''' <param name="pdfFilename">The filename of PDF document.</param>
Public Shared Sub CreateBookmarks(pdfFilename As String)
    ' open PDF document in read-write mode
    Dim document As New Vintasoft.Imaging.Pdf.PdfDocument(pdfFilename)

    ' if PDF document does not contain bookmark collection
    If document.Bookmarks Is Nothing Then
        ' create bookmark collection of PDF document
        document.Bookmarks = New Vintasoft.Imaging.Pdf.Tree.PdfBookmarkCollection(document)
    End If

    ' get bookmarks collection
    Dim bookmarks As Vintasoft.Imaging.Pdf.Tree.PdfBookmarkCollection = document.Bookmarks

    If bookmarks.Count > 1 Then
        ' delete first bookmark
        bookmarks.RemoveAt(0)
        ' delete last bookmark
        bookmarks.RemoveAt(bookmarks.Count - 1)
    End If

    ' create first bookmark
    Dim firstBookmark As New Vintasoft.Imaging.Pdf.Tree.PdfBookmark(document)
    firstBookmark.Title = "First Page"
    firstBookmark.Flags = Vintasoft.Imaging.Pdf.Tree.PdfBookmarkFlags.Bold
    firstBookmark.Destination = New Vintasoft.Imaging.Pdf.Tree.PdfDestinationFit(document, document.Pages(0))

    ' create last bookmark
    Dim lastBookmark As New Vintasoft.Imaging.Pdf.Tree.PdfBookmark(document)
    lastBookmark.Title = "Last Page"
    lastBookmark.Flags = Vintasoft.Imaging.Pdf.Tree.PdfBookmarkFlags.Bold
    lastBookmark.Destination = New Vintasoft.Imaging.Pdf.Tree.PdfDestinationFit(document, document.Pages(document.Pages.Count - 1))

    ' insert first bookmark
    bookmarks.Insert(0, firstBookmark)

    ' add last bookmark
    bookmarks.Add(lastBookmark)

    ' save document
    document.SaveChanges()

    ' close document
    document.Dispose()
End Sub


Изменение закладки

Чтобы изменить закладку, необходимо сделать следующее:
Вот код на C#/VB.NET, который демонстрирует, как изменить текст закладки:
/// <summary>
/// Changes title of the first bookmark of PDF document.
/// </summary>
/// <param name="pdfFilename">The filename of PDF document.</param>
public static void ChangeFirstBookmarkTitle(string pdfFilename)
{
    // open PDF document
    using (Vintasoft.Imaging.Pdf.PdfDocument document = 
        new Vintasoft.Imaging.Pdf.PdfDocument(pdfFilename))
    {
        // get the first bookmark of PDF document
        Vintasoft.Imaging.Pdf.Tree.PdfBookmark bookmark = document.Bookmarks[0];
        // change title of bookmark
        bookmark.Title = "First bookmark";

        // save changes to a file
        document.SaveChanges();
    }
}
''' <summary>
''' Changes title of the first bookmark of PDF document.
''' </summary>
''' <param name="pdfFilename">The filename of PDF document.</param>
Public Shared Sub ChangeFirstBookmarkTitle(pdfFilename As String)
    ' open PDF document
    Using document As New Vintasoft.Imaging.Pdf.PdfDocument(pdfFilename)
        ' get the first bookmark of PDF document
        Dim bookmark As Vintasoft.Imaging.Pdf.Tree.PdfBookmark = document.Bookmarks(0)
        ' change title of bookmark
        bookmark.Title = "First bookmark"

        ' save changes to a file
        document.SaveChanges()
    End Using
End Sub


Удаление закладки

Чтобы удалить закладку, необходимо сделать следующее:
Вот код на C#/VB.NET, который демонстрирует, как удалить все закладки из PDF-документа:
/// <summary>
/// Removes all bookmarks of PDF document.
/// </summary>
/// <param name="pdfFilename">The filename of PDF document.</param>
public static void RemoveAllBookmarks(string pdfFilename)
{
    // open PDF document
    using (Vintasoft.Imaging.Pdf.PdfDocument document = 
        new Vintasoft.Imaging.Pdf.PdfDocument(pdfFilename))
    {
        // get the collection of bookmark of PDF document
        Vintasoft.Imaging.Pdf.Tree.PdfBookmarkCollection bookmarks = document.Bookmarks;

        // if PDF document has bookmarks
        if (bookmarks != null)
            // clear bookmarks of PDF document
            bookmarks.Clear();

        // save changes to a file
        document.SaveChanges();
    }
}
''' <summary>
''' Removes all bookmarks of PDF document.
''' </summary>
''' <param name="pdfFilename">The filename of PDF document.</param>
Public Shared Sub RemoveAllBookmarks(pdfFilename As String)
    ' open PDF document
    Using document As New Vintasoft.Imaging.Pdf.PdfDocument(pdfFilename)
        ' get the collection of bookmark of PDF document
        Dim bookmarks As Vintasoft.Imaging.Pdf.Tree.PdfBookmarkCollection = document.Bookmarks

        ' if PDF document has bookmarks
        If bookmarks IsNot Nothing Then
            ' clear bookmarks of PDF document
            bookmarks.Clear()
        End If

        ' save changes to a file
        document.SaveChanges()
    End Using
End Sub


Действие закладки

Любая закладка может иметь действие, которое будет выполняться при ее выборе.

Вот код на C#/VB.NET, который демонстрирует, как назначить действие для закладки:
/// <summary>
/// Changes action of the first bookmark of PDF document.
/// </summary>
/// <param name="pdfFilename">The filename of PDF document.</param>
public static void ChangeFirstBookmarkAction(string pdfFilename)
{
    // open PDF document
    using (Vintasoft.Imaging.Pdf.PdfDocument document = 
        new Vintasoft.Imaging.Pdf.PdfDocument(pdfFilename))
    {
        // create goto action to the last page of PDF document
        Vintasoft.Imaging.Pdf.Tree.PdfDestinationFit dest = 
            new Vintasoft.Imaging.Pdf.Tree.PdfDestinationFit(document, document.Pages[document.Pages.Count - 1]);
        Vintasoft.Imaging.Pdf.Tree.PdfGotoAction newAction = 
            new Vintasoft.Imaging.Pdf.Tree.PdfGotoAction(dest);
        
        // get the first bookmark of PDF document
        Vintasoft.Imaging.Pdf.Tree.PdfBookmark bookmark = document.Bookmarks[0];
        // change the action of bookmark
        bookmark.Action = newAction;

        // save changes to a file
        document.SaveChanges();
    }
}
''' <summary>
''' Changes action of the first bookmark of PDF document.
''' </summary>
''' <param name="pdfFilename">The filename of PDF document.</param>
Public Shared Sub ChangeFirstBookmarkAction(pdfFilename As String)
    ' open PDF document
    Using document As New Vintasoft.Imaging.Pdf.PdfDocument(pdfFilename)
        ' create goto action to the last page of PDF document
        Dim dest As New Vintasoft.Imaging.Pdf.Tree.PdfDestinationFit(document, document.Pages(document.Pages.Count - 1))
        Dim newAction As New Vintasoft.Imaging.Pdf.Tree.PdfGotoAction(dest)

        ' get the first bookmark of PDF document
        Dim bookmark As Vintasoft.Imaging.Pdf.Tree.PdfBookmark = document.Bookmarks(0)
        ' change the action of bookmark
        bookmark.Action = newAction

        ' save changes to a file
        document.SaveChanges()
    End Using
End Sub



Встраиваемые миниатюры PDF страниц

PDF страницы могут иметь встроенную миниатюру. В большинстве случаев встроенная миниатюра используется только для страниц с изображениями, т. е. для страниц, представляющих собой отсканированные изображения.

Встроенную миниатюру можно получить с помощью свойства PdfPage.Thumbnail.

Также миниатюру страницы можно получить с помощью метода PdfPage.GetThumbnail. Метод возвращает встроенную миниатюру, если она существует и соответствует запрашиваемым размерам. В противном случае метод генерирует миниатюру страницы динамически.


Создание встроенных миниатюр страниц

Встроенную миниатюру страницы можно создать с помощью метода PdfPage.CreateThumbnail. Встроенные миниатюры всех страниц можно создать с помощью метода PdfPageCollection.CreateThumbnails.

Вот код на C#/VB.NET, который демонстрирует, как создать встроенную миниатюру указанной страницы:
/// <summary>
/// Creates an embedded thumbnail of PDF page.
/// </summary>
/// <param name="pdfFilename">The filename of PDF document.</param>
/// <param name="pageIndex">Index of PDF page.</param>
public static void CreateEmbeddedThumbnailOfPdfPage(string pdfFilename, int pageIndex)
{
    // open PDF document in read-write mode
    Vintasoft.Imaging.Pdf.PdfDocument document = 
        new Vintasoft.Imaging.Pdf.PdfDocument(pdfFilename);

    // get the page at the specified index
    Vintasoft.Imaging.Pdf.Tree.PdfPage page = document.Pages[pageIndex];

    // renderer thumbnail with size 128 x 128 pixels
    using (Vintasoft.Imaging.VintasoftImage pageThumbnail = page.Render(128, 128))
    {
        // set page thumbnail
        page.Thumbnail = new Vintasoft.Imaging.Pdf.Tree.PdfImageResource(
            document, pageThumbnail, Vintasoft.Imaging.Pdf.PdfCompression.Jpeg);
    }

    // save changes
    document.SaveChanges();

    // close document
    document.Dispose();
}
''' <summary>
''' Creates an embedded thumbnail of PDF page.
''' </summary>
''' <param name="pdfFilename">The filename of PDF document.</param>
''' <param name="pageIndex">Index of PDF page.</param>
Public Shared Sub CreateEmbeddedThumbnailOfPdfPage(pdfFilename As String, pageIndex As Integer)
    ' open PDF document in read-write mode
    Dim document As New Vintasoft.Imaging.Pdf.PdfDocument(pdfFilename)

    ' get the page at the specified index
    Dim page As Vintasoft.Imaging.Pdf.Tree.PdfPage = document.Pages(pageIndex)

    ' renderer thumbnail with size 128 x 128 pixels
    Using pageThumbnail As Vintasoft.Imaging.VintasoftImage = page.Render(128, 128)
        ' set page thumbnail
        page.Thumbnail = New Vintasoft.Imaging.Pdf.Tree.PdfImageResource(document, pageThumbnail, Vintasoft.Imaging.Pdf.PdfCompression.Jpeg)
    End Using

    ' save changes
    document.SaveChanges()

    ' close document
    document.Dispose()
End Sub


Удаление встроенных миниатюр страниц

Встроенную миниатюру страницы можно удалить с помощью метода PdfPage.RemoveThumbnail. Встроенные миниатюры всех страниц можно удалить с помощью метода PdfPageCollection.RemoveThumbnails.

Вот код на C#/VB.NET, который демонстрирует, как сохранять встроенные миниатюры PDF-страниц на диск и удалять встроенные миниатюры из PDF-документа:
/// <summary>
/// Saves embedded thumnails of PDF document to files and
/// removes the embedded thumbnails from PDF document.
/// </summary>
/// <param name="pdfFilename">The filename of PDF document.</param>
public void SaveAndRemoveEmbeddedThumbnailsOfPdfDocument(string pdfFilename)
{
    // open PDF document in read-write mode
    Vintasoft.Imaging.Pdf.PdfDocument document = 
        new Vintasoft.Imaging.Pdf.PdfDocument(pdfFilename);

    // get the page collection
    Vintasoft.Imaging.Pdf.Tree.PdfPageCollection pages = document.Pages;

    bool hasEmbeddedThumbnails = false;

    // for each PDF page
    for (int i = 0; i < pages.Count; i++)
    {
        // if page has embedded thumbnail
        if (pages[i].Thumbnail != null)
        {
            // mark that PDF document has the embedded thumbnails for pages
            hasEmbeddedThumbnails = true;

            // get thumbnail as image
            using (Vintasoft.Imaging.VintasoftImage img = pages[i].Thumbnail.GetImage())
            {
                // save image to a file
                img.Save("page" + i.ToString() + "_thumb.png");
            }
        }
    }

    // if PDF document has the embedded thumbnails for pages
    if (hasEmbeddedThumbnails)
    {
        // remove embedded thumbnailsfrom PDF document
        document.Pages.RemoveThumbnails();

        // save changes
        document.SaveChanges();
    }

    // close document
    document.Dispose();
}
''' <summary>
''' Saves embedded thumnails of PDF document to files and
''' removes the embedded thumbnails from PDF document.
''' </summary>
''' <param name="pdfFilename">The filename of PDF document.</param>
Public Sub SaveAndRemoveEmbeddedThumbnailsOfPdfDocument(pdfFilename As String)
    ' open PDF document in read-write mode
    Dim document As New Vintasoft.Imaging.Pdf.PdfDocument(pdfFilename)

    ' get the page collection
    Dim pages As Vintasoft.Imaging.Pdf.Tree.PdfPageCollection = document.Pages

    Dim hasEmbeddedThumbnails As Boolean = False

    ' for each PDF page
    For i As Integer = 0 To pages.Count - 1
        ' if page has embedded thumbnail
        If pages(i).Thumbnail IsNot Nothing Then
            ' mark that PDF document has the embedded thumbnails for pages
            hasEmbeddedThumbnails = True

            ' get thumbnail as image
            Using img As Vintasoft.Imaging.VintasoftImage = pages(i).Thumbnail.GetImage()
                ' save image to a file
                img.Save("page" & i.ToString() & "_thumb.png")
            End Using
        End If
    Next

    ' if PDF document has the embedded thumbnails for pages
    If hasEmbeddedThumbnails Then
        ' remove embedded thumbnailsfrom PDF document
        document.Pages.RemoveThumbnails()

        ' save changes
        document.SaveChanges()
    End If

    ' close document
    document.Dispose()
End Sub