bla*_*011 3 pdf password-protection ios swift
我想为我的应用程序中的现有pdf文件添加密码保护。
这是我的代码:
if let path = Bundle.main.path(forResource: "pdf_file", ofType: "pdf") {
let url = URL(fileURLWithPath: path)
if let pdfDocument = PDFDocument(url: url) {
pdfDocument.write(to: url, withOptions: [PDFDocumentWriteOption.userPasswordOption : "pwd"])
pdfView.displayMode = .singlePageContinuous
pdfView.autoScales = true
// pdfView.displayDirection = .horizontal
pdfView.document = pdfDocument
}
}
Run Code Online (Sandbox Code Playgroud)
查看文件之前添加了pdfDocument.write()行。我期望该文件将不再被查看,或者在查看该文件之前会先询问密码,但是我仍然可以直接查看该文件,就像该行不存在一样。
我在将密码保护添加到pdf文件之前和之后尝试过PSPDFKit,当查看该文件时,它会先询问密码,并且应用程序存储中的文件已被锁定/加密,但这不是我使用此iOS时得到的内容iOS 11及更高版本的PDFKit新功能。
您不加密pdfDocument的问题是将pdfDocument的加密副本写入磁盘,如果您从磁盘读取此文档,它将受到保护。例:
if let path = Bundle.main.path(forResource: "pdf_file", ofType: "pdf") {
let url = URL(fileURLWithPath: path)
if let pdfDocument = PDFDocument(url: url) {
let documentDirectory = try! FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor:nil, create:false)
let encryptedFileURL = documentDirectory.appendingPathComponent("encrypted_pdf_file")
// write with password protection
pdfDocument.write(to: encryptedFileURL, withOptions: [PDFDocumentWriteOption.userPasswordOption : "pwd",
PDFDocumentWriteOption.ownerPasswordOption : "pwd"])
// get encrypted pdf
guard let encryptedPDFDoc = PDFDocument(url: encryptedFileURL) else {
return
}
print(encryptedPDFDoc.isEncrypted) // true
print(encryptedPDFDoc.isLocked) // true
pdfView?.displayMode = .singlePageContinuous
pdfView?.autoScales = true
pdfView?.displayDirection = .horizontal
pdfView?.document = encryptedPDFDoc
}
}
Run Code Online (Sandbox Code Playgroud)
希望有帮助
| 归档时间: |
|
| 查看次数: |
759 次 |
| 最近记录: |