ios - 使用 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 时得到的适用于 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
}
}
我希望这有帮助
推荐阅读
- python - 我正在使用 while 语句构建一个函数,并且只要 while 语句结束,它就什么也不做,尽管有更多的代码
- pysnmp - 将模块限定的 OID 转换为 ObjectIdentity
- javascript - 获取浏览器视口的宽度和高度,无论内容的大小如何且不调整为 100%?
- javascript - 当TAB不活跃或API失败时,Settimeout在Angular 4中没有调用
- google-sheets - 具有行的 AverageIF 的数组公式
- python - 在 Python 中创建文件时没有这样的文件或目录
- javascript - 使用 REGEX 'Lookbehind' 作为可选将长字符串拆分成块
- sql - 如何在雪花查询中使用百分比关键字
- flutter - 无法加载资产(在 android studio 中颤动)
- c++ - 包括 c++ 库是否不区分大小写?