如何在Swift中以编程方式创建PDF正确添加密码?

时间:2018-11-04 21:04:26

标签: ios swift pdf

当前,我正在以以下方式创建PDF:

func drawPDFUsingPrintPageRenderer(printPageRenderer: UIPrintPageRenderer) -> NSData! {
    let data = NSMutableData()

    UIGraphicsBeginPDFContextToData(data, CGRect(x: 0, y: 0, width: A4PageHeight, height: A4PageWidth), nil)
    UIGraphicsBeginPDFPage()

    printPageRenderer.drawPage(at: 0, in: UIGraphicsGetPDFContextBounds())

    UIGraphicsEndPDFContext()

    return data
}

通过使用页面渲染器:

let printPageRenderer = CustomPrintPageRenderer()
let printFormatter = UIMarkupTextPrintFormatter(markupText: self.getHTML())
printPageRenderer.addPrintFormatter(printFormatter, startingAtPageAt: 0)

,然后尝试根据以下数据创建PDF:

let pdfData = printPageRenderer.drawPDFUsingPrintPageRenderer(printPageRenderer: printPageRenderer)
mailComposer.addAttachmentData(pdfData as Data, mimeType: "application/pdf", fileName: "My PDF")

当我为页面渲染器创建新实例时:

class CustomPrintPageRenderer: UIPrintPageRenderer {
let A4PageWidth: CGFloat = 595.2
let A4PageHeight: CGFloat = 841.8

var html: String?

override init() {
    super.init()

    // Specify the frame of the A4 page.
    let pageFrame = CGRect(x: 0.0, y: 0.0, width: A4PageHeight, height: A4PageWidth)

    // Set the page frame.
    self.setValue(NSValue(cgRect: pageFrame), forKey: "paperRect")

    // Set the horizontal and vertical insets (that's optional).
    self.setValue(NSValue(cgRect: pageFrame), forKey: "printableRect")
    self.setValue(1234, forKey: kCGPDFContextUserPassword as String)
    self.setValue(1234, forKey: kCGPDFContextOwnerPassword as String)
}

我正在尝试通过以下方式为其设置密码:

self.setValue(1234, forKey: kCGPDFContextUserPassword as String)
self.setValue(1234, forKey: kCGPDFContextOwnerPassword as String)

但是当我运行代码时,它崩溃并显示错误:

Terminating app due to uncaught exception 'NSUnknownKeyException', reason:  
setValue:forUndefinedKey:]: this class is not key value coding-compliant for the key kCGPDFContextUserPassword.'

我该怎么办,如何解决?我正在谷歌搜索,但找不到有用的东西

1 个答案:

答案 0 :(得分:2)

根据UIGraphicsBeginPDFContextToData的文档,最后一个参数是字典,该字典使用与CGPDFContext相同的辅助键。

kCGPDFContextUserPasswordkCGPDFContextOwnerPassword属于这些辅助键。

因此,您似乎需要在致电UIGraphicsBeginPDFContextToData的过程中设置密码。

let info: [AnyHashable: Any] = [kCGPDFContextUserPassword as String : "1234", kCGPDFContextOwnerPassword as String : "1234"]
UIGraphicsBeginPDFContextToData(data, CGRect(x: 0, y: 0, width: A4PageHeight, height: A4PageWidth), info)