使用PDFKit iOS向现有的pdf文件添加密码保护 [英] Add a password protection to an existing pdf file using PDFKit iOS

查看:426
本文介绍了使用PDFKit iOS向现有的pdf文件添加密码保护的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想为我的应用程序中的现有pdf文件添加密码保护.

I wanted to add a password protection to an existing pdf file in my application.

这是我的代码:

    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()行.我希望不再查看该文件,否则它会先询问密码才能查看该文件,但我仍然可以直接查看该文件,就像该行不存在一样.

Added the line pdfDocument.write() before viewing the file. 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.

在向pdf文件添加密码保护之前和之后,我都尝试过 PSPDFKit ,当查看该文件时,它会先询问密码,并且应用程序存储中的文件已锁定/加密,但这不是在iOS 11及更高版本上使用此iOS PDFKit 新功能时会得到什么.

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.

推荐答案

您不加密pdfDocument的问题,是将pdfDocument的加密副本写入磁盘,如果您从磁盘读取此文档,它将受到保护. 示例:

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

我希望有帮助

这篇关于使用PDFKit iOS向现有的pdf文件添加密码保护的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆