首页 > 解决方案 > 如何使用 Swift 和 PDFKit 在交互式 pdf 文件中使用自定义文本完成注释?

问题描述

我有一个交互式 pdf 文件,我只需要在我的 ios 应用程序中填写它的文本字段。它可以是任何工具,无论是原生的还是非原生的。

它看起来像这样:

在此处输入图像描述

在此处输入图像描述

我需要用任何数据来完成该数组。有可能吗?

使用PDFKit它看起来像这样:

let url = Bundle.main.path(forResource: "a", ofType: "pdf")!
let path = URL(fileURLWithPath: url)
let document = PDFDocument(url: path) //PDFDocument
let page1 = document!.page(at: 0)! //PDFPage
let page2 = document!.page(at: 1)! //PDFPage
let annotations = page1.annotations //[PDFAnnotation] count is 380, voilaa;)

在这里,我可以访问每个注释/文本字段。但问题是:

如何使用自定义字符串填充注释?

我尝试以下事情:

    for annotation in annotations {
        annotation.setValue("bb", forAnnotationKey: PDFAnnotationKey.textLabel)
        annotation.setValue("cc", forAnnotationKey: PDFAnnotationKey.contents)
    }
    let name = "output.pdf"
    let output = URL(fileURLWithPath: NSTemporaryDirectory()).appendingPathComponent(name)
    document.write(to: output)
    let controller = UIActivityViewController(activityItems: [output], applicationActivities: nil)
    present(controller, animated: true)

然后我将它保存到 iBooks ......然后......它是空的;)为什么?bb我的或cc标签在哪里?

标签: iosswiftpdfkit

解决方案


只需widgetStringValue用于您的PDFAnnotation

for annotation in document.page(at: 0)!.annotations {
    annotation.widgetStringValue = "value"
}

推荐阅读