How to Programmatically fill PDF form field using iOS PDFKit
Asked Answered
P

1

5

enter image description here In my application, I have a PDF form based on user input. I force the value in the PDF form. I was using the ILPDFKit pod for doing this in my application (swift 3, but since PDFKit is around in iOS 11, I would to know if this is possible using PDFKit). The code I was using with ILPDFKit was:

// set the pdf form as ILPDFDocument  
let document = ILPDFDocument(resource:"ExamplePDFfrom")

// Manually set a form value for field name (created in adobe acrobat)
document.forms.setValue("David", forFormWithName: "FirstName") 
Polygamous answered 27/9, 2017 at 16:31 Comment(0)
S
14

Updated Answer

@objc func pdfPageChanged() {
    for index in 0..<doc!.pageCount{
        if let page = doc?.page(at: index){
            let annotations = page.annotations
            for annotation in annotations{
                print("Annotation Name :: \(annotation.fieldName ?? "")")
                if annotation.fieldName == "firstName"{
                    annotation.setValue("David", forAnnotationKey: .widgetValue)
                    page.removeAnnotation(annotation)
                    page.addAnnotation(annotation)
                }else if annotation.fieldName == "checkBox"{
                    annotation.buttonWidgetState = .onState
                    page.removeAnnotation(annotation)
                    page.addAnnotation(annotation)
                }
            }
        }
    }
}

doc is Object of PDFDocument

Shilohshim answered 3/10, 2017 at 8:58 Comment(7)
Great job Saurabh, this exactly do the job, thanks a lotPolygamous
There is one question though, how to set radio button and check box value as yes also this method only works on first page what about annotation in 2nd pagePolygamous
for checkboxes you can use "annotation.buttonWidgetState = .onState"Shilohshim
I tried this example, after I opened the pdf page and I do not see any changes in it...Vignette
PDF document's user permissions does not allow annotation modificationsVignette
On some PDFs when using this method the annotation text only displays when you click into the field. It seems if you set the "NeedAppearances" flag to true in the AcroForm dictionary, this problem is handled (because the annotation appearance get regenerated). But is it possible to do this with PDFKit?Lacteous
I know i'm a little late, but using annotation.widgetStringValue = "heeeeloo" instead of setValue for text inputs annotations works on iOS 13.Preadamite

© 2022 - 2024 — McMap. All rights reserved.