密码保护PDF

时间:2013-07-10 16:32:53

标签: objective-c cocoa-touch passwords pdf-generation

我有一个应用程序,我从视图中创建PDF文件,然后通过电子邮件发送。我用来生成PDF的代码(非常感谢casillic)是这样的:

- (void)createPDFfromUIView:(UIView*)view saveToDocumentsWithFileName:(NSString*)aFilename
{
    // Creates a mutable data object for updating with binary data, like a byte array
    NSMutableData *pdfData = [NSMutableData data];

    // Points the pdf converter to the mutable data object and to the UIView to be converted
    UIGraphicsBeginPDFContextToData(pdfData, aView.bounds, nil);
    UIGraphicsBeginPDFPage();

    CGContextRef pdfContext = UIGraphicsGetCurrentContext();

    [aView.layer renderInContext:pdfContext]; // this line

    // remove PDF rendering context
    UIGraphicsEndPDFContext();

    // Retrieves the document directories from the iOS device
    NSArray* documentDirectories = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask,YES);

    NSString* documentDirectory = [documentDirectories objectAtIndex:0];
    NSString* documentDirectoryFilename = [documentDirectory stringByAppendingPathComponent:@"cherry"];

    [pdfData writeToFile:documentDirectoryFilename atomically:YES];
    NSLog(@"documentDirectoryFileName: %@",documentDirectoryFilename);
}

它工作得很好。但是,我想实现保护PDF密码的能力。因此,如果他们自己通过电子邮件发送PDF,则需要输入密码才能查看。我完全不确定如何做到这一点。我补充说:

   NSMutableDictionary *myDictionary = CFBridgingRelease(CFDictionaryCreateMutable(NULL, 0,
                                             &kCFTypeDictionaryKeyCallBacks,
                                             &kCFTypeDictionaryValueCallBacks));
    CFDictionarySetValue((__bridge CFMutableDictionaryRef)(myDictionary), kCGPDFContextUserPassword, CFSTR("userpassword"));
    CFDictionarySetValue((__bridge CFMutableDictionaryRef)(myDictionary), kCGPDFContextOwnerPassword, CFSTR("ownerpassword"));

我觉得我走在正确的轨道上,但我完全不确定从这里做什么。我已经阅读了有关保护PDF的密码的文档: https://developer.apple.com/library/mac/#documentation/graphicsimaging/conceptual/drawingwithquartz2d/dq_pdf/dq_pdf.html#//apple_ref/doc/uid/TP30001066-CH214-TPXREF101 但这些仍然是我的头脑。

如果有人知道我需要修改此代码以密码保护PDF,那就太棒了。

1 个答案:

答案 0 :(得分:3)

您需要将通话更新为:

UIGraphicsBeginPDFContextToData(pdfData, aView.bounds, nil);

将最后一个参数替换为myDictionary

UIGraphicsBeginPDFContextToData(pdfData, aView.bounds, myDictionary);