2012-03-22 245 views
1

我需要拍攝屏幕截圖並保存爲pdf。我已經完成了保存爲pdf的任務,但我所採用的截圖總是給出一個空白的PDF。我不知道爲什麼。我的代碼如下:截取屏幕截圖

-(IBAction)takeScreenShot 
{ 
if ([[UIScreen mainScreen] respondsToSelector:@selector(scale)]) 
    UIGraphicsBeginImageContextWithOptions(self.view.bounds.size, NO, [UIScreen mainScreen].scale); 
else 
    UIGraphicsBeginImageContext(self.view.bounds.size); 
[self.view.layer renderInContext:UIGraphicsGetCurrentContext()]; 
UIImage *image = UIGraphicsGetImageFromCurrentImageContext(); 
UIImageView *newImage = [[UIImageView alloc] initWithImage:image]; 
UIGraphicsEndImageContext(); 

[self createPDFfromUIView:newImage saveToDocumentsWithFileName:@"SecondScreen1.pdf"]; 
} 


-(void)createPDFfromUIView:(UIImageView*)aView saveToDocumentsWithFileName:(NSString*)aFilename 
{ 
// Creates a mutable data object for updating with binary data, like a byte array 
NSMutableData *pdfData = [NSMutableData data]; 
//CGSize pageSize = CGSizeMake(612, 792); 
// Points the pdf converter to the mutable data object and to the UIView to be converted 
UIGraphicsBeginPDFContextToData(pdfData, aView.bounds, nil); 
UIGraphicsBeginPDFPage(); 

// draws rect to the view and thus this is captured by UIGraphicsBeginPDFContextToData 
//[aView.layer renderInContext:UIGraphicsGetCurrentContext()]; 

// 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:aFilename]; 

// instructs the mutable data object to write its context to a file on disk 
[pdfData writeToFile:documentDirectoryFilename atomically:YES]; 
NSLog(@"documentDirectoryFileName: %@",documentDirectoryFilename); 
} 
+0

這是你自己問題的擴展副本嗎? http://stackoverflow.com/questions/9724378/can-you-download-something-as-pdf-from-an-iphone-app – 2012-03-22 19:14:59

+0

很好,但我遇到了一個問題,在完成任務。以上就我從前面的問題中得到了。但下面的答案是正確的,這種問題排序 – CodeGeek123 2012-03-23 09:42:12

+1

好吧,我看到你的工作。那很好! – 2012-03-23 09:44:05

回答

3

這條註釋掉的行應該將您的圖像寫入pdf。把代碼放回來,它可能會工作。

[aView.layer renderInContext:UIGraphicsGetCurrentContext()]; 

如果這是失敗(沒有錯誤),請確保UIImage *圖像不是空白。

+0

是的,這是完美的。謝謝 :) – CodeGeek123 2012-03-23 09:41:08