PDFKit 是 Apple 提供的框架,用于在 iOS 和 macOS 应用中显示和操作 PDF 文档。在 iOS 11 中,Apple 对 PDFKit 进行了重大更新,增加了注释和标记功能。
import PDFKit
// 创建PDFView
let pdfView = PDFView(frame: view.bounds)
pdfView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
view.addSubview(pdfView)
// 加载PDF文档
if let url = Bundle.main.url(forResource: "sample", withExtension: "pdf") {
pdfView.document = PDFDocument(url: url)
}
// 添加高亮注释
func addHighlightAnnotation(to page: PDFPage, text: String, color: UIColor) {
// 查找文本范围
let selections = page.selectionForRange(pdfView.document!.findString(text, withOptions: .caseInsensitive))
// 创建高亮注释
let highlight = PDFAnnotation(bounds: selections.bounds(for: page), forType: .highlight, withProperties: nil)
highlight.color = color.withAlphaComponent(0.5)
// 添加注释到页面
page.addAnnotation(highlight)
}
// 添加自由文本注释
func addTextAnnotation(to page: PDFPage, text: String, at point: CGPoint) {
let textAnnotation = PDFAnnotation(bounds: CGRect(x: point.x, y: point.y, width: 200, height: 50),
forType: .freeText,
withProperties: nil)
textAnnotation.contents = text
textAnnotation.font = UIFont.systemFont(ofSize: 14)
textAnnotation.color = .blue
page.addAnnotation(textAnnotation)
}
// 保存带注释的PDF
func saveAnnotatedPDF() {
if let document = pdfView.document {
let data = document.dataRepresentation()
try? data?.write(to: URL(fileURLWithPath: "/path/to/save.pdf"))
}
}
原因:
解决方案:
// 确保使用document的dataRepresentation()方法保存
if let document = pdfView.document {
let data = document.dataRepresentation()
// 保存data到文件
}
原因:
解决方案:
// 使用正确的坐标系转换
let pageBounds = page.bounds(for: .cropBox)
let annotationBounds = selections.bounds(for: page).applying(CGAffineTransform(translationX: 0, y: -pageBounds.height))
原因:
解决方案:
没有搜到相关的文章