ios - 使用 UITextField 中的信息填写 PDF 文档

标签 ios swift ios-pdfkit

我有一个 PDF 文档存储在我的应用程序的主包中,还有一个带有用于用户输入的文本字段的 ViewController。我还有一个按钮可以将填写好的 PDF 通过电子邮件发送给用户。我不需要将 PDF 保存到设备

我想使用 PDFKit 来做到这一点,但我一直无法弄清楚如何实现。

我尝试了以下代码:

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)
    }
}

如有任何帮助,我们将不胜感激。

乔希

最佳答案

我认为你可以替换行:

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

annotation.contents = firstnameField.text

如果这不起作用(也许这不是文本或自由文本注释),您还可以创建自由文本注释并将其放在那里:

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

希望这对您有所帮助。

关于ios - 使用 UITextField 中的信息填写 PDF 文档,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54652543/

相关文章:

iOS PDFKit在PDFView中调整pdf框架

ios - 交互式键盘总是弹跳有问题-它也在弹跳 collectionView 的背景

ios - Apple 是否允许使用套接字在两个 iOS 应用程序之间进行通信?

ios - 可以在 viewDidLoad 中使用 layoutIfNeeded 来确定角半径大小吗?

ios - 如何注册一个类而不是为 UITableViewCell 创建一个 xib

ios - 如何使用 PDFKit 突出显示 pdf 中选定的文本?

ios - 单击按钮时在 UITableViewCell 中添加/删除 subview 和约束

ios - viewForFooterInSection 没有让 UITableView Footer 粘在底部?

objective-c - 将 Objective-C typedef 转换为 Swift 枚举后避免 "Interface type cannot be statically allocated"

ios - 使用swift将图像转换为A4大小的pdf