有没有办法在点击时存储 pdf 注释?

Is there a way to store a pdf annotation on a click?

我正在构建一个机器学习应用程序来读取 pdf 信息,为了训练我的算法,我需要获取 pdf 注释位置。有没有办法设置手势识别器并在单击时将注释添加到数组?我成功地将注释添加到正则表达式的 pdf 中。但是我需要添加注释及其相关信息(单击时在文档中的位置)我可以向应用程序添加手势识别器吗?我的应用程序使用 SwiftUI。

func makeNSView(context: NSViewRepresentableContext<PDFViewRepresentedView>) -> PDFViewRepresentedView.NSViewType {
    let pdfView = PDFView()
    let document = PDFDocument(url: url)
    let regex = try! NSRegularExpression(pattern: #"[0-9.,]+(,|\.)\d\d"#, options: .caseInsensitive)
    let string = document?.string!
    let results = regex.matches(in: string!, options: .withoutAnchoringBounds, range: NSRange(0..<(string?.utf16.count)!))
    let page = document?.page(at: 0)!
    results.forEach { (result) in
        let startIndex = result.range.location
        let endIndex = result.range.location + result.range.length - 1
        let selection = document?.selection(from: page!, atCharacterIndex: startIndex, to: page!, atCharacterIndex: endIndex)
        print(selection!.bounds(for: page!))
        let pdfAnnotation = PDFAnnotation(bounds: (selection?.bounds(for: page!))!, forType: .square, withProperties: nil)
        document?.page(at: 0)?.addAnnotation(pdfAnnotation)
    }
    pdfView.document = document
    return pdfView
}

并获得水龙头

func annotationTapping(_ sender: NSClickGestureRecognizer){
    print("------- annotationTapping ------")
}

如果有人通过添加观察者或类似的东西实现了这一点?

谢谢

PDFView 已经为注释附加了点击手势识别器,因此无需再添加一个。当点击发生时,它会发布一个 PDFViewAnnotationHit 通知。可以在 userInfo.

中找到注释对象

makeUIView 或其他任何有意义的地方设置通知观察者。

NotificationCenter.default.addObserver(forName: .PDFViewAnnotationHit, object: nil, queue: nil) { (notification) in
      if let annotation = notification.userInfo?["PDFAnnotationHit"] as? PDFAnnotation {
        print(annotation.debugDescription)
      }
    }

或更好,在您的 SwiftUI 视图中处理通知。

 @State private var selectedAnnotation: PDFAnnotation?
  
  var body: some View {
    VStack {
      Text("Selected Annotation Bounds: \(selectedAnnotation?.bounds.debugDescription ?? "none")")
      SomeView()
        .onReceive(NotificationCenter.default.publisher(for: .PDFViewAnnotationHit)) { (notification) in
          if let annotation = notification.userInfo?["PDFAnnotationHit"] as? PDFAnnotation {
            self.selectedAnnotation = annotation
          }
      }
    }
  }