iOS PDFKit : make Text Widget PDFAnnotation readonly

标签 ios swift pdfkit pdf-annotations

我想将文本小部件 PDFAnnotation 设置为只读。我尝试将 isReadOnly 标志设置为 true,但似乎没有任何区别。用户在点击后仍然可以编辑注释。

最佳答案

我已经研究这个问题一段时间了,我终于找到了可行的方法。我的解决方案是在 .freeText 上使用 .widget。此方法可防止文本在导出后被选中和修改。我应该指出,PDF 并非万无一失,任何 PDF 都可以反编译,但对于日常办公室工作人员来说,这是一个完美的解决方案。

 //Don't use this - This is what most tutorials show
 //Which can be easily changed after export
 let annotation = PDFAnnotation(bounds: CGRect(x: 10 , y: 720 , width: 100, height: 50), forType: .freeText, withProperties: nil)

使用这个 - Swift 5

func addText(x: Int, y: Int, width: Int, height: Int, text: String, fontSize: CGFloat, centerText: Bool){
    
    //I'm using a PDFView but, if you are not displaying the PDF in the app then just use
    //let fileURL = Bundle.main.url(forResource: "MyPDF", withExtension: "pdf")!
    //let pdfDocument = PDFDocument(url: fileURL)
    //guard let document = pdfDocument else { return }

    guard let document = pdfView.document else { return }
    //I'm only using one page for my PDF but this is easy to change
    let lastPage = document.page(at: document.pageCount - 1)
    let annotation = PDFAnnotation(bounds: CGRect(x: x , y: y, width: width, height: height), forType: .widget, withProperties: nil)

    //Don't use contents and caption
    //annotation.contents = text
    //annotation.caption = text

    //Use this instead
    annotation.widgetFieldType = .text
    annotation.widgetStringValue = text

    //Check if the text should be centered
    if (centerText){ annotation.alignment = .center }

    //I'm using a custom font 
    annotation.font = UIFont(name: "calibri", size: fontSize)
    //You can use this instead
    //annotation.font = UIFont.systemFont(ofSize: fontSize)

    //Set the color
    annotation.fontColor = .black
    annotation.color = .clear
    annotation.backgroundColor = .clear

    //This is useless 
    annotation.isReadOnly = true

    //Add the annotation to the last page
    lastPage?.addAnnotation(annotation)
    
}

关于iOS PDFKit : make Text Widget PDFAnnotation readonly,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49941644/

相关文章:

ios - 连接到多个剪辑录音机的麦克风使应用程序崩溃

ios - 如何使单元格适合 Collection View

ios - Parse.com 查询无法正常工作

ios - 获取在 QLPreview Controller 中显示的 PDF 的尺寸

ruby-on-rails - PDFKit 不会在 Ubuntu on rails 上呈现

iphone - 如何在 objective-c 中创建自定义类集群 ..?

ios - 如何使用 ENUM 作为方法的参数

ios - Realm - 将带有初始数据的文件添加到项目 (iOS/Swift)

ruby-on-rails - 在 S3 上存储系统生成的 PDF

swift - PDFKit iOS11 Swift 4 如何显示表格?