【发布时间】:2020-09-11 21:09:50
【问题描述】:
我想在 pdf 中搜索一个正则表达式,并使用正则表达式的结果为其添加注释。我已经建立了一个简单的函数来做到这一点。正如令人惊叹的社区(用他们的时间帮助我的真正了不起的人)发布的那样,我可以使用 decomposedStringWithCompatibilityMapping 在 pdf 中正确搜索所需的表达式,但之后当我执行 pdf 选择时找到它的界限,我遇到了不同。我把我的代码和一些图片发给你。
func performRegex(regex:String, on pdfPage:PDFPage) {
guard let pdfString = pdfPage.string?.precomposedStringWithCanonicalMapping else { return }
guard let safeRegex = try? NSRegularExpression(pattern: regex, options: .caseInsensitive) else { return }
let results = safeRegex.matches(in: pdfString, options: .withoutAnchoringBounds, range: NSRange(pdfString.startIndex..., in: pdfString))
pdfPage.annotations.forEach { pdfPage.removeAnnotation($0)}
results.forEach { result in
let bbox = pdfPage.selection(for: result.range)?.bounds(for: pdfPage)
let annotation = PDFAnnotation(bounds: bbox!, forType: .highlight, withProperties: nil)
annotation.color = .yellow
annotation.contents = String(pdfString[Range(result.range, in:pdfString)!])
pdfPage.addAnnotation(annotation)
}
}
问题是,当我这样做并输入这个表达式 [0-9] 时,我的所有结果都发生了变化:
如果我不使用 precomposedStringWithCanonicalMapping,我的所有结果都不会移动,但是当我得到一个特殊字符时会遇到错误。
问题(我怀疑)出在这行代码中。
let bbox = pdfPage.selection(for: result.range)?.bounds(for: pdfPage)
但我不知道有什么工作要做。
如果有人可以帮助我,请给我一些帮助!
非常感谢
【问题讨论】:
-
问题是您使用的是 decomposedStringWithCompatibilityMapping 范围。您需要找到一种方法来转换该范围。
-
有没有办法将pdf原始字符串替换为decomposedStringWithCompatibilityMapping字符串?我认为这将是最简单的解决方案。
-
我看到字符串和属性字符串属性都是get only
-
我现在能想到的唯一选择是使用原始字符串并修复格式错误的范围。
-
在下面查看我的帖子
标签: ios swift xcode ios-pdfkit