【问题标题】:Add a password protection to an existing pdf file using PDFKit iOS使用 PDFKit iOS 为现有 pdf 文件添加密码保护
【发布时间】:2019-03-10 16:58:24
【问题描述】:

我想在我的应用程序中为现有的 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 及更高版本中使用此 iOS PDFKit 新功能时,我得到了什么。

【问题讨论】:

    标签: ios swift pdf password-protection pdfkit


    【解决方案1】:

    您没有加密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
        }
    }
    

    希望对你有帮助

    【讨论】:

    • 很好,帮了很多忙。我的代码中有 2 个错误,我如何编写密码保护,我注意到 .userPassword 和 .ownerPassword 必须同时存在才能锁定和加密 pdf 文件。另一个正在查看 pdfDocument,我需要再次访问加密的 pdfDocument,这就是我需要显示的 pdfDocument。非常感谢。
    • @black1011 我很高兴你)
    猜你喜欢
    • 2018-11-06
    • 2012-09-05
    • 1970-01-01
    • 2017-11-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-09-30
    相关资源
    最近更新 更多