Convert Screenshot to PDF in Xcode? - iphone

How might one convert a screenshot, taken on an iPhone for example, into a PDF file. It's easy enough to take the screenshot and put it into a UIImage, but it's the conversion which has me stumped. I took a look at the Quartz framework which is the only one in Xcode that I know to support the PDF format, but couldn't find anything there to make this work. Is there anything native to Xcode that I'm missing? If not, is there a public framework somewhere that could handle a conversion like this?

I figured it out. It involved saving a screenshot as a UIImage, and then using the very helpful tutorial found here to get me going with the PDF conversion. As it turns out, there are functions to handle the making of PDF documents in the Core Graphics class.

You wouldn't convert a screenshot to a pdf. You would create a screenshot, create a pdf and insert the screenshot image into the first page of the pdf.
Untested code to create image:
nameStr = [NSString stringWithFormat:#"myImage.png"];
fileManager = [NSFileManager defaultManager];
paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
documentsDirectory = [paths objectAtIndex:0];
namePath = [documentsDirectory stringByAppendingString:#"/"];
namePath = [thumbnailPath nameStr];
CGRect contextRect = CGRectMake(0, 0, 1024, 768);
UIGraphicsBeginImageContext(contextRect.size);
[self.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage *viewImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
NSData *data = UIImagePNGRepresentation(viewImage);
UIImage *myImage = [[UIImage alloc] initWithData:data];
Untested code to add image to a pdf:
pageSize = CGSizeMake(1024, 768);
fileName = #"myFile.pdf";
pdfFileName = [documentsDirectory stringByAppendingPathComponent:fileName];
UIGraphicsBeginPDFContextToFile(pdfFileName, CGRectZero, nil);
UIGraphicsBeginPDFPageWithInfo(CGRectMake(0, 0, pageSize.width, pageSize.height), nil);
[myImage drawInRect:CGRectMake( 0, 0, 1024, 768];
UIGraphicsEndPDFContext();
p.s. assuming ipad 1024 x 768 above

Related

IPhone crashes when capturing multiple images and also slows down

I'm developing an application where I need to capture multiple images and store them in a folder. The application crashes when the images exceed.Also while taking images IPhone slows down a bit. Please anyone can help me with this.
code fo capturing image
UIImagePickerController *picker=[[UIImagePickerController alloc]init];
picker.delegate=self;
picker.sourceType=UIImagePickerControllerSourceTypeCamera;
[self.navigationController presentModalViewController:picker animated:YES];
Code for adding images into file
NSString *pngImagePath =
[[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
NSUserDomainMask, YES) lastObject]
stringByAppendingPathComponent:[NSString
stringWithFormat:#"%#.png",imageName]];
[dataImage writeToFile:pngImagePath atomically:YES];
Here, take this code as example to resize images before you show them on the screen:
+ (UIImage*)imageWithImage:(UIImage*)image
scaledToSize:(CGSize)newSize;
{
UIGraphicsBeginImageContext( newSize );
[image drawInRect:CGRectMake(0,0,newSize.width,newSize.height)];
UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return newImage;
}
Notice that you should also reduce the images before you save them to the disk:
UIImage *image = YOUR_IMAGE;
NSData *imageData = UIImageJPEGRepresentation(image, .06); // Here's the level of compression
Just try with #autoreleasepool once, may be its due to some memory leaks. #autoreleasepool with maintain upto some extent..
#autoreleasepool
{
// any allocation for UIImage if u have just bring inside the autoreleasepool
NSString *pngImagePath =
[[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
NSUserDomainMask, YES) lastObject]
stringByAppendingPathComponent:[NSString
stringWithFormat:#"%#.png",imageName]];
[dataImage writeToFile:pngImagePath atomically:YES];
}

Take a screenshot of screen

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);
}
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.

UIImagePickerController - Save and Load Image?

There seems to be a scatter of info on this topic, but it seems rather a muddle, so I hoe you don't mind me asking.
I have a UIImagePickerController working, letting me either take a photo or pick on from the library and then set a UIImageView of my choice to show that image taken/selected.
However, how can I firstly save the image, then load it back in when the application is reopened? Also, I will be saving multiple images so they need to be uniquely identified.
Any help will be massively appreciated, thanks.
I don't know of a way to get the Photo from the Photo Album a Second time. There does not seem to be a way to retrieve it again. We do a few things to save the Image internally.
We either convert the Image to NSData and save it in CoreData, or we save it off to our sandbox.
here is a snip of code that we use, this is doing one of a few things, I'm getting the Image from a ScreenShot, though its the same once you have the UIImage.
// go get our screenshot
UIImage* screenShot = [self createScreenShotThumbnailWithWidth:200];
// Save screen shot as a png in the documents directory with the UUID of the IoCDScreen
// Saving to Sandbox
[self saveImage:screenShot withName:currentScreen.itemUUID];
// save image to Photo Album - though you can't get a ref back to it
UIImageWriteToSavedPhotosAlbum(screenShot, self, nil, nil);
//convert our screen shot PNG to NSData and store it in a CoreData Managed Object
currentScreen.screenImageDevelopment = [NSData dataWithData: UIImagePNGRepresentation( screenShot )];
Helper Functions used above
//--------------------------------------------------------------------------------------------------------
// saveImage:withName:
// Description: Save the Image with the name to the Documents folder
//
//--------------------------------------------------------------------------------------------------------
- (void)saveImage:(UIImage *)image withName:(NSString *)name {
//grab the data from our image
NSData *data = UIImageJPEGRepresentation(image, 1.0);
//get a path to the documents Directory
NSFileManager *fileManager = [NSFileManager defaultManager];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
// Add out name to the end of the path with .PNG
NSString *fullPath = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:#"%#.png", name]];
//Save the file, over write existing if exists.
[fileManager createFileAtPath:fullPath contents:data attributes:nil];
}
//--------------------------------------------------------------------------------------------------------
// createScreenShotThumbnailWithWidth
// Description: Grab a screen shot and then scale it to the width supplied
//
//--------------------------------------------------------------------------------------------------------
-(UIImage *) createScreenShotThumbnailWithWidth:(CGFloat)width{
// Size of our View
CGSize size = self.view.bounds.size;
//First Grab our Screen Shot at Full Resolution
UIGraphicsBeginImageContext(size);
[self.view.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage *screenShot = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
//Calculate the scal ratio of the image with the width supplied.
CGFloat ratio = 0;
if (size.width > size.height) {
ratio = width / size.width;
} else {
ratio = width / size.height;
}
//Setup our rect to draw the Screen shot into
CGRect rect = CGRectMake(0.0, 0.0, ratio * size.width, ratio * size.height);
//Scale the screenshot and save it back into itself
UIGraphicsBeginImageContext(rect.size);
[screenShot drawInRect:rect];
screenShot = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
//Send back our screen shot
return screenShot;
}

ios save web page as pdf

Can someone point me in the right direction for saving a webpage as a pdf? I already have a library for an iOS pdf reader, but I need to somehow implement a feature for saving whatever webpage the user is viewing as pdf. I am assuming I would have to use an in-app browser. Any thoughts?
This is not something that I have done, but it seems you are not the first to want to do something like this.
http://www.iphonedevsdk.com/forum/iphone-sdk-development/21451-save-contents-uiwebview-pdf-file.html
The last post in this link provides code to save a UIWebView as an image, and you should be able to convert that image into a PDF. I don't take credit for the code as I did not write it, just connecting you two :)
Here is the code for simplicity:
CGSize sixzevid=CGSizeMake(1024,1100);
UIGraphicsBeginImageContext(sixzevid);
[webview.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage *viewImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
NSData *imageData = UIImagePNGRepresentation(viewImage);
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *pathFloder = [[NSString alloc] initWithString:[NSString stringWithFormat:#"%#",#"new.png"]];
NSString *defaultDBPath = [documentsDirectory stringByAppendingPathComponent:pathFloder];
[imageData writeToFile:defaultDBPath atomically:YES];
Chances are pretty good that you will have to tweak this but, hopefully this helps you move in the right direction.

How to adjust a image size after using UIImagePickerController take a photo?

How to resize a image when save photo in document folder ???
This is how I save an image in iphone.
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *imageFile = nil;
NSString *name_png = [NSString stringWithFormat:#"%#.png",photoName];
imageFile = [documentsDirectory stringByAppendingPathComponent:name_png];
[UIImagePNGRepresentation(self.theImageView.image) writeToFile:imageFile atomically:YES];
How to resize it from original size to 200 X 200 pixels?
Or can I load the image file than resize it?
Actually, I was create a cover flow with many images, and the image was from camera.
I can find a cover flow sample, but when I load image, it full of iphone screen.
Not a small cover image.
UIImage resize : Go thru this link.
Thanks to Paul Lynch.
+ (UIImage *)imageWithImage:(UIImage *)image scaledToSize:(CGSize)newSize {
UIGraphicsBeginImageContextWithOptions(newSize, NO, 0.0);
[image drawInRect:CGRectMake(0, 0, newSize.width, newSize.height)];
UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return newImage;
}