Reputation: 4980
I have an app in which I create a PDF file from the view, then email it. The code I'm using to generate the PDF (much thanks to casillic) is this:
- (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);
}
It is working perfectly. However, I would like to implement the ability to have the PDF password protected. So that if they email themselves the PDF, the will need to enter in a password in order to view it. I'm totally unsure of how to do this. I added in:
NSMutableDictionary *myDictionary = CFBridgingRelease(CFDictionaryCreateMutable(NULL, 0,
&kCFTypeDictionaryKeyCallBacks,
&kCFTypeDictionaryValueCallBacks));
CFDictionarySetValue((__bridge CFMutableDictionaryRef)(myDictionary), kCGPDFContextUserPassword, CFSTR("userpassword"));
CFDictionarySetValue((__bridge CFMutableDictionaryRef)(myDictionary), kCGPDFContextOwnerPassword, CFSTR("ownerpassword"));
I feel like I'm on the right track, but I'm totally unsure of what to do from here. I've read the docs about passcode protecting a PDF: https://developer.apple.com/library/mac/#documentation/graphicsimaging/conceptual/drawingwithquartz2d/dq_pdf/dq_pdf.html#//apple_ref/doc/uid/TP30001066-CH214-TPXREF101 But these still go over my head.
If anyone knows how I need to modify this code to password protect the PDF, that would be awesome.
Upvotes: 1
Views: 1187
Reputation: 318954
You need to update the call to:
UIGraphicsBeginPDFContextToData(pdfData, aView.bounds, nil);
by replacing the last parameter with myDictionary
.
UIGraphicsBeginPDFContextToData(pdfData, aView.bounds, myDictionary);
Upvotes: 3