2013-07-10 255 views
1

我有一個應用程序,我從視圖中創建一個PDF文件,然後通過電子郵件發送。我使用生成PDF(多感謝casillic)的代碼是這樣的:密碼保護PDF

- (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,那就太棒了。

回答

3

您需要更新調用:用myDictionary替換最後一個參數

UIGraphicsBeginPDFContextToData(pdfData, aView.bounds, nil); 

UIGraphicsBeginPDFContextToData(pdfData, aView.bounds, myDictionary); 
+0

太棒了,非常感謝rmaddy! – John