简体   繁体   English

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

[英]Add a password protection to an existing pdf file using PDFKit iOS

I wanted to add a password protection to an existing pdf file in my application.我想为应用程序中的现有 pdf 文件添加密码保护。

Here's my code:这是我的代码:

    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
        }
    }

Added the line pdfDocument.write() before viewing the file.在查看文件之前添加了pdfDocument.write()行。 I was expecting that the file wouldn't be viewed anymore or it would ask a password first before it can be viewed but i can still view it directly as if that line did not exist.我原以为不会再查看该文件,或者它会在查看之前先询问密码,但我仍然可以直接查看它,就好像该行不存在一样。

I tried PSPDFKit before and when i add a password protection to a pdf file, when viewing the file it asks a password first and the file in the application storage is locked/encrypted, but that's not what I'm getting when I used this iOS PDFKit new feature for iOS 11 and later.我之前尝试过PSPDFKit ,当我向 pdf 文件添加密码保护时,在查看文件时它首先要求输入密码并且应用程序存储中的文件被锁定/加密,但这不是我使用此 iOS 时得到的适用于 iOS 11 及更高版本的PDFKit新功能。

Your problem that you don't encrypt pdfDocument, you write encrypted copy of pdfDocument to disk, if you read this document from disk, it is will be protected.你的问题是你没有加密pdfDocument,你将pdfDocument的加密副本写入磁盘,如果你从磁盘读取这个文档,它会受到保护。 Example:例子:

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
    }
}

I hope this help我希望这有帮助

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM