我想只读取Text Widget PDFAnnotation。我尝试将 isReadOnly 标记设置为 true ,但它似乎没有任何区别。用户仍然可以在点击后编辑注释。
答案 0 :(得分:0)
PDFKit不支持注释的isReadOnly属性似乎是一个错误/疏忽。但是,我可以通过在文档中的其他注释上添加空白注释来解决此问题。我在PDF文档中添加了一个 makeReadOnly()扩展名,该扩展名用于所有注释,以使整个文档只读。这是代码:
// A blank annotation that does nothing except serve to block user input
class BlockInputAnnotation: PDFAnnotation {
init(forBounds bounds: CGRect, withProperties properties: [AnyHashable : Any]?) {
super.init(bounds: bounds, forType: PDFAnnotationSubtype.stamp, withProperties: properties)
self.fieldName = "blockInput"
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func draw(with box: PDFDisplayBox, in context: CGContext) {
}
}
extension PDFDocument {
func makeReadOnly() {
for pageNumber in 0..<self.pageCount {
guard let page = self.page(at: pageNumber) else {
continue
}
for annotation in page.annotations {
annotation.isReadOnly = true // This _should_ be enough, but PDFKit doesn't recognize the isReadOnly attribute
// So we add a blank annotation on top of the annotation, and it will capture touch/mouse events
let blockAnnotation = BlockInputAnnotation(forBounds: annotation.bounds, withProperties: nil)
blockAnnotation.isReadOnly = true
page.addAnnotation(blockAnnotation)
}
}
}
}
答案 1 :(得分:0)
我已经在解决这个问题上有一段时间了,终于找到了行之有效的方法。对我来说,解决方案是在.widget
上使用.freeText
。此方法可防止在导出后选择和修改文本。我应该指出,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)
使用此功能-迅速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)
}