1

I need to take a screen shot of a screen and save as pdf. I have accomplished the save as pdf task however the screenshot i take always gives a blank pdf. I have no idea why. My code is as follows :

 -(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);
}
CodeGeek123
  • 4,341
  • 8
  • 50
  • 79
  • Is this expanded duplicate of your own question? http://stackoverflow.com/questions/9724378/can-you-download-something-as-pdf-from-an-iphone-app – Rok Jarc Mar 22 '12 at 19:14
  • Well sort of but i encountered a problem in accomplishing the task. The above is as far as i got from the previous question. But the answer below is correct and that sorts the problem – CodeGeek123 Mar 23 '12 at 09:42
  • 1
    Ok, i see you got it working. That's good! – Rok Jarc Mar 23 '12 at 09:44

1 Answers1

3

This line that's commented out should be writing your image to the pdf. Put that code back in and it might work.

[aView.layer renderInContext:UIGraphicsGetCurrentContext()];

If that's failing (with no errors) make sure that UIImage *image is not blank.

Nate
  • 539
  • 3
  • 14