iospdfpdf-generationpodofo

Update Widgets in PDF using Podofo


I am using PdfAnnotation.SetContents to set the value of an annotation.If the annotation is of type FreeText, only then this method correctly works and the value gets displayed on the PDF (using PDF Reader).If the type is Widget, the value gets set as content in pdf dictionary but does not get displayed.Is there a way i could set the value of a widget?


Solution

  • I found the solution, In order for the content to get displayed, an Appearance ("AP") Dictionary has to be set.

    This could be used for that:

    void PdfField::CreateFieldAppearance(PdfMemDocument *memDoc, const PdfString &value)
    {
      if( !m_pWidget->HasAppearanceStream() )
      {
        PdfRect pageRect;
        PdfPainter painter;
    
        PoDoFo::PdfRect rect = this->GetWidgetAnnotation()->GetRect();
        unsigned int width = rect.GetWidth();
        unsigned int height = rect.GetHeight();
    
        PdfRect pdfRect(0, 0, width, height);    
    
        PdfXObject xObj(pdfRect, memDoc);
        painter.SetPage(&xObj);
        painter.SetClipRect(pdfRect);
    
        painter.Save();
        painter.SetColor(221.0/255.0, 228.0/255.0, 1.0);
    
        painter.FillRect(0, 0, width, height);
        painter.Restore();
    
        // make rotation
    
        painter.Save();
    
        /***********************************************************************************/
    
        // Rotation Logic
    
        double angle = this->GetPage()->GetRotation();
    
        if (angle) {
            double radAngle = angle * M_PI / 180;
    
            int cosA =  (int)cos(radAngle);
            int sinA = (int)sin(radAngle);
    
            double translateY = rect.GetWidth(); // The View goes out of the bound, sits on top
            painter.SetTransformationMatrix(cosA, sinA, -sinA, cosA, translateY, 0);
        }
        /***********************************************************************************/
    
    
        PdfFont *font = memDoc->CreateFont("Helvetica", true, false);
        font->SetFontSize(15);     
    
        // Do the drawing
        painter.SetFont(font);
        painter.BeginText(10, 5);
        painter.SetStrokeWidth(20);
        painter.AddText(value);
        painter.EndText();
    
        painter.FinishPage();
    
        // This is very important. Not only does it disable the editing.
        // Also it does correct the appearance issue on Adobe Readers.
        this->SetReadOnly(true);
    
        // The Stream Object has to be saved to the annotation
        PoDoFo::PdfDictionary dict;
        dict.AddKey( "N", xObj.GetObject()->Reference() );
        this->GetFieldObject()->GetDictionary().AddKey( "AP", dict );
    }
    
    }