Search code examples
c#pdftronpdfnet

Drawing a rectangle annotation with PDFTron (PdfNet)


I'm trying to a the user create a rectangle in a pdf. The user can drag a rectangle on the screen.

on the mouseup event, a Rect object is created and passed to the method AddRectAnnotationToPage(Rectangle rect)

The problem is that the rectangle annotation differs from the rect the user dragged. When the user clicks or scrolls, the annotation rectangle gets it's correct size (equal to the dragged rect that was passed as an argument)

Why does it not take it's correct size immediately? and why does it resizes to the correct size whenever i click on a random spot in the pdf?

    private void AddRectAnnotationToPage(Rectangle rect)
    {
        if (rect != null)
        {
            if (this.m_pageNumber < 0)
            {
                m_pageNumber = this.GetCurrentPage();
            }

            _cur_page = this.m_pageNumber;

            if (_cur_page < 0)
            {
                return;
            }


            double width = rect.Width;
            double height = rect.Height;

            double startX = rect.Left;
            double startY = rect.Bottom;
            double endX   = rect.Right;
            double endY   = rect.Top;

            double X1 = startX;
            double Y1 = startY;
            double X2 = endX;
            double Y2 = endY;

            ConvScreenPtToPagePt(ref X1, ref Y1, this.GetCurrentPage());
            ConvScreenPtToPagePt(ref X2, ref Y2, this.GetCurrentPage());

            Rect pos = new Rect(X1,Y1,X2,X2);
            Polygon poly = pdftron.PDF.Annots.Polygon.Create(m_PdfDocument.GetSDFDoc(), pos);
            pdftron.PDF.Point p = new pdftron.PDF.Point();
            p.x = X1; p.y = Y1;
            poly.SetVertex (0, p);
            p.x = X1; p.y = Y2;
            poly.SetVertex (1, p);
            p.x = X2; p.y = Y2;
            poly.SetVertex (2, p);
            p.x = X2; p.y = Y1;
            poly.SetVertex (3, p);


            PDFDoc doc = GetDoc();
            doc.Lock();
            pdftron.PDF.Page pag = doc.GetPage(_cur_page);

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

            pag.AnnotPushBack(poly);
            doc.Unlock();
        }
    }

Solution

  • Fixed by calling Refreshappearance() after setting the vertices