1

I have a PDF document stored in the main bundle of my app and a ViewController with text fields for user input. I also have a button to email the filled out PDF to the user. I do not need to save the PDF to the device

I would like to use PDFKit to do this, but I haven't been able to figure out how this can be achieved.

I have attempted the following code:

if let path = Bundle.main.path(forResource: "User", ofType: "pdf") {
    let url = URL(fileURLWithPath: path)
    if let doc = PDFDocument(url: url) {

        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(firstnameField.text, forAnnotationKey: .widgetValue)
                        page.removeAnnotation(annotation)
                        page.addAnnotation(annotation)
                    }
                }
            }
        }
        let mailComposer = MFMailComposeViewController()
        mailComposer.mailComposeDelegate = self
        mailComposer.setToRecipients([emailField.text])
        mailComposer.setSubject("User Information")
        mailComposer.setMessageBody("User Information for \(firstnameField.text).", isHTML: true)
        mailComposer.addAttachmentData(doc.dataRepresentation()!, mimeType: "application/pdf", fileName: "User")
        self.present(mailComposer, animated: true, completion: nil)
    }
}

Any help with this would be greatly appreciated.

Josh

Marcy
  • 4,611
  • 2
  • 34
  • 52
J. Wood
  • 43
  • 4

1 Answers1

0

I think you can replace line:

annotation.setValue(firstnameField.text, forAnnotationKey: .widgetValue)

with

annotation.contents = firstnameField.text

If this doesn't work (maybe this is not a text or freetext annotation), you can also create freetext annotation and put it there:

let textObj = PDFAnnotation(bounds: annotation.bounds, forType: .freeText, withProperties: nil)
textObj.contents = firstnameField.text
textObj.color = UIColor.clear
page.addAnnotation(textObj)

Hope this helps.

qtngo
  • 1,594
  • 1
  • 11
  • 13
  • Thank you! Adding a new annotation is what worked for me, for some reason the fields that I added in Acrobat weren't working. – J. Wood Feb 12 '19 at 18:40