Some test text!

menu
search
chevron_right UWP samples

Add or edit PDF annotations in C# (UWP)

Sample C# (UWP) code to use PDFTron SDK for adding or editing PDF annotations. The annotation types included in this sample are: hyperlink, intra-document link, stamp, rubber stamp, file attachment, sound, text, free-text, line, circle, square, polygon, polyline, highlight, squiggly, caret, and ink. Learn more about our PDF Annotation Library.

To run this sample, get started with a free trial of PDFTron SDK.

using System;
using System.IO;
using System.Threading.Tasks;
using Windows.Foundation;

using pdftron.PDF;
using pdftron.SDF;

using PDFNetUniversalSamples.ViewModels;

namespace PDFNetSamples
{
    //-----------------------------------------------------------------------------------------
    // This sample shows how to add a text annotation to an existing page and how to create
    // link annotations between several pages.
    //-----------------------------------------------------------------------------------------
    public sealed class AnnotationTest : Sample
    {
        public AnnotationTest() :
            base("Annotation", "This sample shows how to add a text annotation to an existing page and how to create link annotations between several pages.")
        {
        }

        public override IAsyncAction RunAsync()
        {
            return Task.Run(new System.Action(async() => {
                WriteLine("--------------------------------");
                WriteLine("Starting Annotation Test...");
                WriteLine("--------------------------------\n");
                try
                {
                    String input_file_path = Path.Combine(InputPath, "numbered.pdf");
                    WriteLine("Opening input file " + input_file_path);
                    PDFDoc doc = new PDFDoc(input_file_path);
                    doc.InitSecurityHandler();

                    // An example of using SDF/Cos API to add any type of annotations.
                    AnnotationLowLevelAPI(doc);
                    String output_file_path = Path.Combine(OutputPath, "annotation_test1.pdf");
                    await doc.SaveAsync(output_file_path, SDFDocSaveOptions.e_linearized);
                    WriteLine("Done. Results saved in " + output_file_path);
                    await AddFileToOutputList(output_file_path).ConfigureAwait(false);

                    // An example of using the high-level PDFNet API to read existing annotations,
                    // to edit existing annotations, and to create new annotation from scratch.
                    AnnotationHighLevelAPI(doc);
                    output_file_path = Path.Combine(OutputPath, "annotation_test2.pdf");
                    await doc.SaveAsync(output_file_path, SDFDocSaveOptions.e_linearized);
                    WriteLine("Done. Results saved in " + output_file_path);
                    await AddFileToOutputList(output_file_path).ConfigureAwait(false);

                    doc.Destroy();
                }
                catch (Exception e)
                {
                    WriteLine(GetExceptionMessage(e));
                }

                WriteLine("\n--------------------------------");
                WriteLine("Done Annotation Test.");
                WriteLine("--------------------------------\n");
            })).AsAsyncAction();
        }

        void AnnotationLowLevelAPI(PDFDoc doc)
        {
            pdftron.PDF.Page page = doc.GetPage(1);

            Obj annots = page.GetAnnots();
            if (annots == null)
            {
                // If there are no annotations, create a new annotation 
                // array for the page.
                annots = doc.CreateIndirectArray();
                page.GetSDFObj().Put("Annots", annots);
            }

            // Create the Text annotation
            Obj text_annot = doc.CreateIndirectDict();
            text_annot.PutName("Subtype", "Text");
            text_annot.PutBool("Open", true);
            text_annot.PutString("Contents", "The quick brown fox ate the lazy mouse.");
            text_annot.PutRect("Rect", 266, 116, 430, 204);

            // Insert the annotation in the page annotation array
            annots.PushBack(text_annot);

            // Create a Link annotation
            Obj link1 = doc.CreateIndirectDict();
            link1.PutName("Subtype", "Link");
            pdftron.PDF.Page p = doc.GetPage(2);
            Destination dest = Destination.CreateFit(p);
            link1.Put("Dest", dest.GetSDFObj());
            link1.PutRect("Rect", 85, 705, 503, 661);
            annots.PushBack(link1);

            // Create another Link annotation
            Obj link2 = doc.CreateIndirectDict();
            link2.PutName("Subtype", "Link");
            Destination dest2 = Destination.CreateFit(doc.GetPage(3));
            link2.Put("Dest", dest2.GetSDFObj());
            link2.PutRect("Rect", 85, 638, 503, 594);
            annots.PushBack(link2);

            // Note that PDFNet APi can be used to modify existing annotations. 
            // In the following example we will modify the second link annotation 
            // (link2) so that it points to the 10th page. We also use a different 
            // destination page fit type.

            link2.Put("Dest", Destination.CreateXYZ(doc.GetPage(10), 100, 792 - 70, 10).GetSDFObj());

            // Create a third link annotation with a hyperlink action (all other 
            // annotation types can be created in a similar way)
            Obj link3 = doc.CreateIndirectDict();
            link3.PutName("Subtype", "Link");
            link3.PutRect("Rect", 85, 570, 503, 524);

            // Create a URI action
            Obj action = link3.PutDict("A");
            action.PutName("S", "URI");
            action.PutString("URI", "http://www.pdftron.com");
            annots.PushBack(link3);
        }

        void AnnotationHighLevelAPI(PDFDoc doc)
        {
            // The following code snippet traverses all annotations in the document
            WriteLine("Traversing all annotations in the document...");

            PageIterator itr = doc.GetPageIterator();
            for (; itr.HasNext(); itr.Next())
            {
                WriteLine(String.Format("Page {0:d}: ", itr.GetPageNumber()));

                pdftron.PDF.Page page = itr.Current();
                int num_annots = page.GetNumAnnots();
                for (int i = 0; i < num_annots; ++i)
                {
                    IAnnot annot = page.GetAnnot(i);
                    if (annot.IsValid() == false) continue;
                    WriteLine(String.Format("Annot Type: {0:s}", annot.GetSDFObj().Get("Subtype").Value().GetName()));

                    pdftron.PDF.Rect bbox = annot.GetRect();
                    WriteLine(String.Format("  Position: {0:f}, {1:f}, {2:f}, {3:f}", bbox.x1, bbox.y1, bbox.x2, bbox.y2));

                    switch (annot.GetAnnotType())
                    {
                        case AnnotType.e_Link:
                            pdftron.PDF.Annots.Link lk = (pdftron.PDF.Annots.Link)annot;
                            pdftron.PDF.Action action = lk.GetAction();
                            if (action.GetType() == pdftron.PDF.ActionType.e_GoTo)
                            {
                                Destination dest = action.GetDest();
                                if (dest.IsValid() == false)
                                    WriteLine(" Not a valid destination.");
                                else
                                {
                                    int page_num = dest.GetPage().GetIndex();
                                    WriteLine(String.Format("  Links to: page number {0:d} in this document", page_num));
                                }
                            }
                            else if (action.GetType() == pdftron.PDF.ActionType.e_URI)
                            {
                                System.String uri = action.GetSDFObj().Get("URI").Value().GetAsPDFText();
                                WriteLine(String.Format("  Links to: {0:s}", uri));
                            }
                            break;
                        case AnnotType.e_Widget:
                            break;
                        case AnnotType.e_FileAttachment:
                            break;
                        default:
                            break;
                    }

                }
            }

            // Use the high-level API to create new annotations.
            pdftron.PDF.Page first_page = doc.GetPage(1);

            // Create an intra-document link...
            pdftron.PDF.Action goto_page_3 = pdftron.PDF.Action.CreateGoto(Destination.CreateFitH(doc.GetPage(3), 0));
            pdftron.PDF.Annots.Link link2 = pdftron.PDF.Annots.Link.Create(doc.GetSDFDoc(), new pdftron.PDF.Rect(85, 458, 503, 502), goto_page_3);
             
            // Set the annotation border width to 3 points...
            link2.SetBorderStyle(new pdftron.PDF.AnnotBorderStyle(AnnotBorderStyleStyle.e_solid, 3));
            link2.SetColor(new pdftron.PDF.ColorPt(0, 0, 1), 3);

            // Add the new annotation to the first page
            first_page.AnnotPushBack(link2);

            // Create a stamp annotation ...
            pdftron.PDF.Annots.RubberStamp stamp = pdftron.PDF.Annots.RubberStamp.Create(doc.GetSDFDoc(), new pdftron.PDF.Rect(30, 30, 300, 200));
            stamp.SetIcon("Approved");
            first_page.AnnotPushBack(stamp);

            // Create a file attachment annotation (embed the 'peppers.jpg').
            pdftron.PDF.Annots.FileAttachment file_attach = pdftron.PDF.Annots.FileAttachment.Create(doc.GetSDFDoc(), new pdftron.PDF.Rect(80, 280, 200, 320), Path.Combine(InputPath, "peppers.jpg"));
            first_page.AnnotPushBack(file_attach);

            //Create a highlight annotation. 
            pdftron.PDF.Annots.Highlight higlight = pdftron.PDF.Annots.Highlight.Create(doc.GetSDFDoc(), new pdftron.PDF.Rect(85, 570, 503, 524));
            higlight.SetQuadPoint(0, new QuadPoint(new pdftron.PDF.Point(85, 524), new pdftron.PDF.Point(503, 524), new pdftron.PDF.Point(503, 524), new pdftron.PDF.Point(85, 570)));
            pdftron.PDF.Annots.Popup pp = pdftron.PDF.Annots.Popup.Create(doc.GetSDFDoc(), new pdftron.PDF.Rect(130, 280, 100, 150));
            pp.SetOpen(true);
            pp.SetColor(new pdftron.PDF.ColorPt(1, 0, 0), 3);
            pp.SetFlag(AnnotFlag.e_hidden, false);
            pp.SetFlag(AnnotFlag.e_invisible, false);
            pp.SetUniqueID("I am a popup");
            pp.SetBorderStyle(new AnnotBorderStyle(AnnotBorderStyleStyle.e_dashed, 5));
            pp.SetDate(new Date(09, 02, 23, 05, 19, 00));
            higlight.SetColor(new ColorPt(1, 0, 1, 0), 4);
            higlight.SetPopup(pp);
            first_page.AnnotPushBack(higlight);

            //Create an ink annotation. 
            pdftron.PDF.Annots.Ink ink = pdftron.PDF.Annots.Ink.Create(doc.GetSDFDoc(), new pdftron.PDF.Rect(110, 10, 300, 200));
            pdftron.PDF.Point pt3 = new pdftron.PDF.Point();
            pt3.x = 110; pt3.y = 10;
            ink.SetPoint(0, 0, pt3);
            pt3.x = 150; pt3.y = 50;
            ink.SetPoint(0, 1, pt3);
            pt3.x = 190; pt3.y = 60;
            ink.SetPoint(0, 2, pt3);
            pt3.x = 180; pt3.y = 90;
            ink.SetPoint(1, 0, pt3);
            pt3.x = 190; pt3.y = 95;
            ink.SetPoint(1, 1, pt3);
            pt3.x = 200; pt3.y = 100;
            ink.SetPoint(1, 2, pt3);
            pt3.x = 166; pt3.y = 86;
            ink.SetPoint(2, 0, pt3);
            pt3.x = 196; pt3.y = 96;
            ink.SetPoint(2, 1, pt3);
            pt3.x = 221; pt3.y = 121;
            ink.SetPoint(2, 2, pt3);
            pt3.x = 288; pt3.y = 188;
            ink.SetPoint(2, 3, pt3);
            ink.SetColor(new ColorPt(0, 1, 1), 3);
            first_page.AnnotPushBack(ink);

            // Create a Sticky Note
            pdftron.PDF.Annots.Text txt = pdftron.PDF.Annots.Text.Create(doc.GetSDFDoc(), new pdftron.PDF.Rect(161, 388, 180, 406), "Hello World");
            // Create a 'pop-up' annotation associated with the sticky note.
            pdftron.PDF.Annots.Popup pop = pdftron.PDF.Annots.Popup.Create(doc.GetSDFDoc(), new pdftron.PDF.Rect(272, 300, 450, 450));
            pop.SetParent(txt);
            txt.SetPopup(pop);
            txt.SetColor(new ColorPt(1, 0, 0));
            txt.RefreshAppearance();

            // Add annotations to the page.
            first_page.AnnotPushBack(txt);
            first_page.AnnotPushBack(pop);
        }
    }
}
close

Free Trial

Get unlimited trial usage of PDFTron SDK to bring accurate, reliable, and fast document processing capabilities to any application or workflow.

Select a platform to get started with your free trial.

Unlimited usage. No email address required.

PDFTron Receives USD$71 Million Growth Investment Led By Silversmith Capital Partners

Learn More
close