Search code examples
swiftpdfpdfkit

PDFKit annotation saving text annotation


I have a 100 page PDF document that my app opens up. In my document there are various textfield that I have added to allow the user to add comments. I have tried various ways to save the text in the textboxes to allow the user to return tp editing/marking up the document, but I am without luck. How can I save the text in the PDFAnotoation TextBox as an annotated string to allow the user to pickup where they left off when editing?

Here is my original:

var textFieldMultiline21 = PDFAnnotation()    
let textFieldMultilineBounds21 = CGRect(x: 27, y: 58+2, width: 339, height: 508)
textFieldMultiline21 = PDFAnnotation(bounds: textFieldMultilineBounds21, forType: PDFAnnotationSubtype(rawValue: PDFAnnotationSubtype.widget.rawValue), withProperties: nil)
textFieldMultiline21.widgetFieldType = PDFAnnotationWidgetSubtype(rawValue: PDFAnnotationWidgetSubtype.text.rawValue)
textFieldMultiline21.backgroundColor = UIColor.clear
textFieldMultiline21.font = UIFont.systemFont(ofSize: 18)
textFieldMultiline21.isMultiline = true
page.addAnnotation(textFieldMultiline21)

Here I say attempt in saving the text inside the text boxes:

document.page(at: 21)?.annotations[0].contents = "Sample text"
textFieldMultiline21.caption = "sampletext"

Solution

  • Somewhat of a simple answer that was hiding in plain sight

    Reading Text

    pdfAnnotationTextField.value(forAnnotationKey: .widgetValue)
    

    returns a string value with attributes

    Setting Text

    pdfAnnotationTextField.setValue("Enter Text", forAnnotationKey: .widgetValue)