使用 PDFKit iOS 为现有 pdf 文件添加密码保护



我想为应用程序中的现有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
}
}

在查看文件之前添加了pdfDocument.write((行。我预计该文件将不再被查看,或者它会先询问密码才能查看,但我仍然可以直接查看它,就好像那行不存在一样。

我之前尝试过PSPDFKit,当我为 pdf 文件添加密码保护时,在查看文件时,它首先询问密码,并且应用程序存储中的文件被锁定/加密,但这不是我在使用 iOS 11 及更高版本的 iOSPDFKit新功能时得到的。

你的问题,你不加密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
}
}

我希望这有帮助

最新更新