簡體   English   中英

使用 PDFKit iOS 為現有 pdf 文件添加密碼保護

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

我想為應用程序中的現有 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
    }
}

我希望這有幫助

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM