【问题标题】:Extract PDF Highlights with PDFKit使用 PDFKit 提取 PDF 亮点
【发布时间】:2019-10-03 15:19:33
【问题描述】:

我正在尝试在 macOS 应用程序中使用 PDFkit 提取所有亮点。这是我正在使用的代码:

guard let path = item.filePath else { return }

let document = PDFDocument(url: URL(fileURLWithPath: path))

guard let numberOfPage = document?.pageCount else { return }

for i in 0...numberOfPage - 1 {
   let pages = document?.page(at: i)
   guard let annotations = pages?.annotations else { continue }

   for annotation in annotations {
      if annotation.type == "Highlight" {
        print(annotation.contents)
        self.annotations.append(annotation)
      }
   }
}

问题是print(annotation.contents) 总是返回“Optional("")”。我尝试了几个pdf,结果总是一样的。问题是,如果我执行print(annotation.color),它会返回给定高光的正确颜色。

我的代码有什么我没有弄清楚的问题吗?还是这是 PDFKit 的正常行为?

【问题讨论】:

  • 我对 PDFKit 了解不多,但 "Highlight" 看起来很可疑。也许使用PDFAnnotationSubtype.highlight 有帮助?
  • 我试过但没用,annotation.type 是字符串,PDFAnnotationSubtype.highlight 不是。无论如何,感谢您的尝试;)

标签: swift cocoa pdfkit


【解决方案1】:

使用PDFAnnotationSubtype.highlight.rawValue 获取亮点的关键。如果您打印该值,您将看到它是/Highlight。即使我们现在知道密钥,您仍然应该使用枚举值,以防PDFKit 中发生任何变化。

所以在你的情况下......

if annotation.type == PDFAnnotationSubtype.highlight.rawValue {

如果这让您感到困惑,请熟悉Enums and Raw Values.

【讨论】:

  • 我已经尝试过了,但它不起作用。如果我在里面放了一个print,它就永远不会被调用。我只有在使用annotation.type == "Highlight" 时才会得到回报。我尝试向 PDF 添加注释,并使用annotation.type == "Popup"print(annotation.contents) 之后,它返回一个包含注释内容的字符串。所以看来只有高光有问题……
  • @Herlid 作为for-loop 中的第一条语句,输入以下代码:print(annotation.type.rawValue)。你看到了什么?
  • 我看到 Xcode 抛出错误“'String 类型的值?'没有成员 'rawValue'",因为 annotation.type 是一个字符串。
  • 当然,抱歉。那请用print(annotation.type)试试吧。
  • 我已经检查过了,输出是“Optional("Highlight")”。这就是我如何确定我应该使用annotation.type == "Highlight" 来只提取这种类型。
猜你喜欢
  • 2014-10-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-02-25
  • 2016-02-11
  • 1970-01-01
  • 2016-12-11
  • 1970-01-01
相关资源
最近更新 更多