VintaSoft Imaging .NET SDK 14.0: Документация для .NET разработчика
В этом разделе
    PDF: Работа с PDF аннотациями документа
    В этом разделе
    VintaSoft PDF .NET Plug-in предоставляет функциональность для невизуальной низкоуровневой работы с PDF аннотациями документа.
    Комбинация VintaSoft PDF .NET Plug-in и VintaSoft Annotation .NET Plug-in предоставляет функциональность для полнофункционального визуального и невизуального аннотирования PDF документа в WinForms, WPF и ASP.NET. Подробную информацию о функциональности VintaSoft Annotation .NET Plug-in смотрите здесь .


    Класс PdfAnnotation определяет аннотацию PDF документа и позволяет:
    Здесь представлена иерархия классов, определяющих стандартные аннотации PDF документа:
    Вот C#/VB.NET код, который демонстрирует, как получить информацию о всех аннотациях на PDF странице:
    /// <summary>
    /// Gets and prints information about all annotations of PDF page.
    /// </summary>
    /// <param name="pdfFileName">The filename of PDF document.</param>
    public static void PrintAnnotationsInfo(string pdfFileName)
    {
        // open PDF document
        using (Vintasoft.Imaging.Pdf.PdfDocument document =
            new Vintasoft.Imaging.Pdf.PdfDocument(pdfFileName))
        {
            // for each PDF page
            for (int pageIndex = 0; pageIndex < document.Pages.Count; pageIndex++)
            {
                // get PDF page
                Vintasoft.Imaging.Pdf.Tree.PdfPage page = document.Pages[pageIndex];
                // get a collection of annotations of PDF page
                Vintasoft.Imaging.Pdf.Tree.Annotations.PdfAnnotationList annotations = page.Annotations;
                if (annotations == null)
                {
                    System.Console.WriteLine("Page {0}: no annotations.", pageIndex + 1);
                }
                else
                {
                    // print the page index and count of annotations
                    System.Console.WriteLine("Page {0} Annotation count: {1}", pageIndex + 1, annotations.Count);
                    // for each annotation
                    foreach (Vintasoft.Imaging.Pdf.Tree.Annotations.PdfAnnotation annotation in annotations)
                    {
                        // print information about annotation
                        System.Console.WriteLine("Annotation:");
                        System.Console.WriteLine("           Name: \"{0}\"", annotation.Name);
                        System.Console.WriteLine(" Title (Author): \"{0}\"", annotation.Title);
                        System.Console.WriteLine("        Subject: \"{0}\"", annotation.Subject);
                        System.Console.WriteLine("       Contents: \"{0}\"", annotation.Contents);
                        System.Console.WriteLine("AppearanceState: \"{0}\"", annotation.AppearanceState);
                        System.Console.WriteLine("       Modified: {0}", annotation.Modified);
                        System.Console.WriteLine("          Flags: {0}", annotation.Flags);
                        System.Console.WriteLine();
                    }
                }
            }
        }
    }
    
    ''' <summary>
    ''' Gets and prints information about all annotations of PDF page.
    ''' </summary>
    ''' <param name="pdfFileName">The filename of PDF document.</param>
    Public Shared Sub PrintAnnotationsInfo(pdfFileName As String)
        ' open PDF document
        Using document As New Vintasoft.Imaging.Pdf.PdfDocument(pdfFileName)
            ' for each PDF page
            For pageIndex As Integer = 0 To document.Pages.Count - 1
                ' get PDF page
                Dim page As Vintasoft.Imaging.Pdf.Tree.PdfPage = document.Pages(pageIndex)
                ' get a collection of annotations of PDF page
                Dim annotations As Vintasoft.Imaging.Pdf.Tree.Annotations.PdfAnnotationList = page.Annotations
                If annotations Is Nothing Then
                    System.Console.WriteLine("Page {0}: no annotations.", pageIndex + 1)
                Else
                    ' print the page index and count of annotations
                    System.Console.WriteLine("Page {0} Annotation count: {1}", pageIndex + 1, annotations.Count)
                    ' for each annotation
                    For Each annotation As Vintasoft.Imaging.Pdf.Tree.Annotations.PdfAnnotation In annotations
                        ' print information about annotation
                        System.Console.WriteLine("Annotation:")
                        System.Console.WriteLine("           Name: ""{0}""", annotation.Name)
                        System.Console.WriteLine(" Title (Author): ""{0}""", annotation.Title)
                        System.Console.WriteLine("        Subject: ""{0}""", annotation.Subject)
                        System.Console.WriteLine("       Contents: ""{0}""", annotation.Contents)
                        System.Console.WriteLine("AppearanceState: ""{0}""", annotation.AppearanceState)
                        System.Console.WriteLine("       Modified: {0}", annotation.Modified)
                        System.Console.WriteLine("          Flags: {0}", annotation.Flags)
                        System.Console.WriteLine()
                    Next
                End If
            Next
        End Using
    End Sub
    



    Создание новой PDF аннотации

    Чтобы создать новую PDF аннотацию, необходимо сделать следующее:
    Вот C#/VB.NET код, который демонстрирует, как создать PDF аннотацию, состоящую из красного прямоугольника:
    /// <summary>
    /// Creates an annotation, which consists from red rectangle.
    /// </summary>
    /// <param name="page">The page.</param>
    /// <returns>The created annotation.</returns>
    public static Vintasoft.Imaging.Pdf.Tree.Annotations.PdfAnnotation CreatePdfAnnotation(
        Vintasoft.Imaging.Pdf.Tree.PdfPage page)
    {
        // create a rectangular annotation
        Vintasoft.Imaging.Pdf.Tree.Annotations.PdfSquareAnnotation annotation = 
            new Vintasoft.Imaging.Pdf.Tree.Annotations.PdfSquareAnnotation(page);
        // set interior color
        annotation.InteriorColor = System.Drawing.Color.Red;
        // set rectangle
        annotation.Rectangle = new System.Drawing.RectangleF(40, 40, 160, 80);
        // create graphics for normal appearance
        using (Vintasoft.Imaging.Pdf.Drawing.PdfGraphics pdfGraphics = annotation.CreateNormalAppearanceGraphics())
        {
            // draw an appearance of the annotation
            pdfGraphics.FillRectangle(
                new Vintasoft.Imaging.Pdf.Drawing.PdfBrush(System.Drawing.Color.Red), 
                0, 0, 
                annotation.Rectangle.Width, annotation.Rectangle.Height);
        }
    
        // return created annotation
        return annotation;
    }
    
    ''' <summary>
    ''' Creates an annotation, which consists from red rectangle.
    ''' </summary>
    ''' <param name="page">The page.</param>
    ''' <returns>The created annotation.</returns>
    Public Shared Function CreatePdfAnnotation(page As Vintasoft.Imaging.Pdf.Tree.PdfPage) As Vintasoft.Imaging.Pdf.Tree.Annotations.PdfAnnotation
        ' create a rectangular annotation
        Dim annotation As New Vintasoft.Imaging.Pdf.Tree.Annotations.PdfSquareAnnotation(page)
        ' set interior color
        annotation.InteriorColor = System.Drawing.Color.Red
        ' set rectangle
        annotation.Rectangle = New System.Drawing.RectangleF(40, 40, 160, 80)
        ' create graphics for normal appearance
        Using pdfGraphics As Vintasoft.Imaging.Pdf.Drawing.PdfGraphics = annotation.CreateNormalAppearanceGraphics()
            ' draw an appearance of the annotation
            pdfGraphics.FillRectangle(New Vintasoft.Imaging.Pdf.Drawing.PdfBrush(System.Drawing.Color.Red), 0, 0, annotation.Rectangle.Width, annotation.Rectangle.Height)
        End Using
    
        ' return created annotation
        Return annotation
    End Function
    



    Добавление аннотации на PDF страницу

    Чтобы добавить новую аннотацию на PDF страницу, необходимо сделать следующее:
    Вот C#/VB.NET код, который демонстрирует, как создать аннотацию-линию и добавить ее на PDF страницу:
    /// <summary>
    /// Creates a Line annotation and adds it onto PDF page.
    /// </summary>
    /// <param name="pdfFilename">The filename of PDF document.</param>
    public static void AddLineAnnotationOntoPage(string pdfFilename)
    {
        // open PDF document
        using (Vintasoft.Imaging.Pdf.PdfDocument pdfDocument = new Vintasoft.Imaging.Pdf.PdfDocument(pdfFilename))
        {
            // get first page of the document
            Vintasoft.Imaging.Pdf.Tree.PdfPage page = pdfDocument.Pages[0];
            // create line annotation
            Vintasoft.Imaging.Pdf.Tree.Annotations.PdfLineAnnotation lineAnnotation = 
                new Vintasoft.Imaging.Pdf.Tree.Annotations.PdfLineAnnotation(page);
            // set color of the annotation
            lineAnnotation.Color = System.Drawing.Color.Green;
            // set rectangle of the annotation
            lineAnnotation.Rectangle = page.CropBox;
            // set start point of the annotation
            lineAnnotation.StartPoint = new System.Drawing.PointF(0, 0);
            // set end point of the annotation
            lineAnnotation.EndPoint = new System.Drawing.PointF(page.CropBox.Width, page.CropBox.Height);
            // create graphics for normal appearance
            using (Vintasoft.Imaging.Pdf.Drawing.PdfGraphics pdfGraphics = lineAnnotation.CreateNormalAppearanceGraphics())
            {
                // draw appearance of the annotation
                pdfGraphics.DrawLine(new Vintasoft.Imaging.Pdf.Drawing.PdfPen(System.Drawing.Color.Green, 3f),
                    0, 0, lineAnnotation.Rectangle.Width, lineAnnotation.Rectangle.Height);
            }
            // if there is no annotations
            if (page.Annotations == null)
                // create collection of annotations of the page
                page.Annotations = new Vintasoft.Imaging.Pdf.Tree.Annotations.PdfAnnotationList(pdfDocument);
            // add the annotation to the collection
            page.Annotations.Add(lineAnnotation);
            // save changes to the source
            pdfDocument.SaveChanges();
        }
    }
    
    ''' <summary>
    ''' Creates a Line annotation and adds it onto PDF page.
    ''' </summary>
    ''' <param name="pdfFilename">The filename of PDF document.</param>
    Public Shared Sub AddLineAnnotationOntoPage(pdfFilename As String)
        ' open PDF document
        Using pdfDocument As New Vintasoft.Imaging.Pdf.PdfDocument(pdfFilename)
            ' get first page of the document
            Dim page As Vintasoft.Imaging.Pdf.Tree.PdfPage = pdfDocument.Pages(0)
            ' create line annotation
            Dim lineAnnotation As New Vintasoft.Imaging.Pdf.Tree.Annotations.PdfLineAnnotation(page)
            ' set color of the annotation
            lineAnnotation.Color = System.Drawing.Color.Green
            ' set rectangle of the annotation
            lineAnnotation.Rectangle = page.CropBox
            ' set start point of the annotation
            lineAnnotation.StartPoint = New System.Drawing.PointF(0, 0)
            ' set end point of the annotation
            lineAnnotation.EndPoint = New System.Drawing.PointF(page.CropBox.Width, page.CropBox.Height)
            ' create graphics for normal appearance
            Using pdfGraphics As Vintasoft.Imaging.Pdf.Drawing.PdfGraphics = lineAnnotation.CreateNormalAppearanceGraphics()
                ' draw appearance of the annotation
                pdfGraphics.DrawLine(New Vintasoft.Imaging.Pdf.Drawing.PdfPen(System.Drawing.Color.Green, 3F), 0, 0, lineAnnotation.Rectangle.Width, lineAnnotation.Rectangle.Height)
            End Using
            ' if there is no annotations
            If page.Annotations Is Nothing Then
                ' create collection of annotations of the page
                page.Annotations = New Vintasoft.Imaging.Pdf.Tree.Annotations.PdfAnnotationList(pdfDocument)
            End If
            ' add the annotation to the collection
            page.Annotations.Add(lineAnnotation)
            ' save changes to the source
            pdfDocument.SaveChanges()
        End Using
    End Sub
    



    Удаление аннотации с PDF страницы

    Чтобы удалить аннотацию с PDF страницы, необходимо сделать следующее:
    Вот C#/VB.NET код, который демонстрирует, как удалить аннотацию с PDF страницы:
    /// <summary>
    /// Removes the first annotation from PDF page
    /// if it is a link annotation.
    /// </summary>
    /// <param name="page">The page of PDF document.</param>
    public static bool RemoveAnnotationFromPdfPage(Vintasoft.Imaging.Pdf.Tree.PdfPage page)
    {
        // if annotations exist
        if (page.Annotations != null && page.Annotations.Count > 0)
        {
            // if contents of the first annotation if it is a link
            if (page.Annotations[0] is Vintasoft.Imaging.Pdf.Tree.Annotations.PdfLinkAnnotation)
            {
                // remove the annotation
                page.Annotations.RemoveAt(0);
                return true;
            }
        }
    
        return false;
    }
    
    ''' <summary>
    ''' Removes the first annotation from PDF page
    ''' if it is a link annotation.
    ''' </summary>
    ''' <param name="page">The page of PDF document.</param>
    Public Shared Function RemoveAnnotationFromPdfPage(page As Vintasoft.Imaging.Pdf.Tree.PdfPage) As Boolean
        ' if annotations exist
        If page.Annotations IsNot Nothing AndAlso page.Annotations.Count > 0 Then
            ' if contents of the first annotation if it is a link
            If TypeOf page.Annotations(0) Is Vintasoft.Imaging.Pdf.Tree.Annotations.PdfLinkAnnotation Then
                ' remove the annotation
                page.Annotations.RemoveAt(0)
                Return True
            End If
        End If
    
        Return False
    End Function
    



    Изменение внешнего вида PDF аннотации

    Свойство PdfAnnotation.AppearanceGenerator позволяет получить или установить генератор внешнего вида PDF аннотации. Пользовательский генератор внешнего вида должен быть создан, если необходимо изменить внешний вид аннотации. В PDF Editor Demo есть пример генератора внешнего вида для поля подписи PDF - класс SignatureAppearanceGenerator, который можно найти в файле "<install_path>\Examples\WinForms\CSharp\PdfEditorDemo\DemosCommonCode.Pdf\AnnotationTool\FormFields\AppearanceGenerators\Signature\SignatureAppearanceGenerator.cs".


    Добавление комментариев к PDF аннотации

    Для работы с комментариями на PDF странице необходимо выполнить следующие действия:
    Вот C#/VB.NET код, который демонстрирует, как распечатать комментарии указанного PDF документа:
    /// <summary>
    /// Demonstrates how to prints comments of specified PDF document.
    /// </summary>
    public class PdfAnnotationCommentExample
    {
        /// <summary>
        /// Prints comments of specified PDF document.
        /// </summary>
        /// <param name="pdfFilename">The PDF filename.</param>
        public static void PrintComments(string pdfFilename)
        {
            // create an image collection
            using (Vintasoft.Imaging.ImageCollection images = new Vintasoft.Imaging.ImageCollection())
            {
                // add PDF document to the image collection
                images.Add(pdfFilename);
    
                // create PDF annotation comment controller
                using (Vintasoft.Imaging.Annotation.Comments.Pdf.ImageCollectionPdfAnnotationCommentController pdfAnnotationCommentController =
                    new Vintasoft.Imaging.Annotation.Comments.Pdf.ImageCollectionPdfAnnotationCommentController())
                {
                    // specify that PDF annotation comment controller is associated with image collection
                    pdfAnnotationCommentController.Images = images;
    
                    // print comments from PDF annotation comment controller
                    PrintComments(pdfAnnotationCommentController);
                }
    
                // clear and dispose images
                images.ClearAndDisposeItems();
            }
        }
    
        /// <summary>
        /// Prints comments from specified comment controller.
        /// </summary>
        /// <param name="commentController">The comment controller.</param>
        public static void PrintComments(Vintasoft.Imaging.Annotation.Comments.ImageCollectionCommentController commentController)
        {
            // for each image
            for (int i = 0; i < commentController.Images.Count; i++)
            {
                Vintasoft.Imaging.VintasoftImage image = commentController.Images[i];
    
                // get comment collection, which is associated with image/PDF page
                Vintasoft.Imaging.Annotation.Comments.CommentCollection comments = commentController.GetComments(image);
                // if comments are found
                if (comments != null && comments.Count > 0)
                {
                    System.Console.WriteLine(string.Format("Page {0}:", i + 1));
    
                    // for each comment
                    foreach (Vintasoft.Imaging.Annotation.Comments.Comment comment in comments)
                    {
                        // print comment
                        PrintComment(comment, 0);
                    }
                }
            }
        }
    
        /// <summary>
        /// Prints the comment.
        /// </summary>
        /// <param name="comment">The comment.</param>
        /// <param name="replyLevel">The reply level.</param>
        private static void PrintComment(Vintasoft.Imaging.Annotation.Comments.Comment comment, int replyLevel)
        {
            // print comment
            System.Console.Write(string.Empty.PadLeft(replyLevel * 4));
            System.Console.WriteLine(string.Format("[{0}] {1}: {2} ({3})",comment.Type, comment.UserName, comment.Text, comment.ModifyDate));
    
            // if comment has replies
            if (comment.Replies != null)
            {
                // print replies
                foreach (Vintasoft.Imaging.Annotation.Comments.Comment reply in comment.Replies)
                    PrintComment(reply, replyLevel + 1);
            }
        }
    
    }
    
    
    ''' <summary>
    ''' Demonstrates how to prints comments of specified PDF document.
    ''' </summary>
    Public Class PdfAnnotationCommentExample
        ''' <summary>
        ''' Prints comments of specified PDF document.
        ''' </summary>
        ''' <param name="pdfFilename">The PDF filename.</param>
        Public Shared Sub PrintComments(pdfFilename As String)
            ' create an image collection
            Using images As New Vintasoft.Imaging.ImageCollection()
                ' add PDF document to the image collection
                images.Add(pdfFilename)
    
                ' create PDF annotation comment controller
                Using pdfAnnotationCommentController As New Vintasoft.Imaging.Annotation.Comments.Pdf.ImageCollectionPdfAnnotationCommentController()
                    ' specify that PDF annotation comment controller is associated with image collection
                    pdfAnnotationCommentController.Images = images
    
                    ' print comments from PDF annotation comment controller
                    PrintComments(pdfAnnotationCommentController)
                End Using
    
                ' clear and dispose images
                images.ClearAndDisposeItems()
            End Using
        End Sub
    
        ''' <summary>
        ''' Prints comments from specified comment controller.
        ''' </summary>
        ''' <param name="commentController">The comment controller.</param>
        Public Shared Sub PrintComments(commentController As Vintasoft.Imaging.Annotation.Comments.ImageCollectionCommentController)
            ' for each image
            For i As Integer = 0 To commentController.Images.Count - 1
                Dim image As Vintasoft.Imaging.VintasoftImage = commentController.Images(i)
    
                ' get comment collection, which is associated with image/PDF page
                Dim comments As Vintasoft.Imaging.Annotation.Comments.CommentCollection = commentController.GetComments(image)
                ' if comments are found
                If comments IsNot Nothing AndAlso comments.Count > 0 Then
                    System.Console.WriteLine(String.Format("Page {0}:", i + 1))
    
                    ' for each comment
                    For Each comment As Vintasoft.Imaging.Annotation.Comments.Comment In comments
                        ' print comment
                        PrintComment(comment, 0)
                    Next
                End If
            Next
        End Sub
    
        ''' <summary>
        ''' Prints the comment.
        ''' </summary>
        ''' <param name="comment">The comment.</param>
        ''' <param name="replyLevel">The reply level.</param>
        Private Shared Sub PrintComment(comment As Vintasoft.Imaging.Annotation.Comments.Comment, replyLevel As Integer)
            ' print comment
            System.Console.Write(String.Empty.PadLeft(replyLevel * 4))
            System.Console.WriteLine(String.Format("[{0}] {1}: {2} ({3})", comment.Type, comment.UserName, comment.Text, comment.ModifyDate))
    
            ' if comment has replies
            If comment.Replies IsNot Nothing Then
                ' print replies
                For Each reply As Vintasoft.Imaging.Annotation.Comments.Comment In comment.Replies
                    PrintComment(reply, replyLevel + 1)
                Next
            End If
        End Sub
    
    End Class