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.
Related
I am making an iOS app that saves an image of given URL.
I used the following code.
- (IBAction)save:(id)sender {
UIImage *image = [[UIImage alloc] initWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:photoUrl]]];
NSLog(#"%f,%f",image.size.width,image.size.height);
// Let's save the file into Document folder.
NSString *docDir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSLog(#"saving jpg");
NSString *jpegFilePath = [NSString stringWithFormat:#"%#/test.jpg",docDir];
NSData *data2 = [NSData dataWithData:UIImageJPEGRepresentation(image, 1.0f)];//1.0f = 100% quality
[data2 writeToFile:jpegFilePath atomically:YES];
NSLog(#"saving image done");
}
The image is saved successfully after calling this method.
Since I use iPhone simulator, I can see the image is saved my local Library folder.
However, when I open Photos (iPhone navie app) from the simulator, it doesn't detect the image I just saved.
When I save an image from Safari and open Photos app, it detects the image correctly.
But why can't it detect the image I saved thru my ios app? Any solutions?
How come/why do you think or assume any image written to a random location should be known about by the Photos app? That's just nonsense. Use the UIImageWriteToSavedPhotosAlbum() function instead.
I am creating an iPhone app and in that I want to download multiple image files from web service. And I want to save the images in the local folder in the app itself and save the path to each files in SQLite database. How can I implement this? Please help.
**// Get an image from the URL below**
UIImage *image = [[UIImage alloc] initWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:#"yorimageurl"]]];
NSLog(#"%f,%f",image.size.width,image.size.height);
**// Let's save the file into Document folder.**
NSString *Dir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *pngPath = [NSString stringWithFormat:#"%#/test.png",Dir];// this path if you want save reference path in sqlite
NSData *data1 = [NSData dataWithData:UIImagePNGRepresentation(image)];
[data1 writeToFile:pngFilePath atomically:YES];
NSLog(#"saving jpeg");
NSString *jpegPath = [NSString stringWithFormat:#"%#/test.jpeg",Dir];// this path if you want save reference path in sqlite
NSData *data2 = [NSData dataWithData:UIImageJPEGRepresentation(image, 1.0f)];//1.0f = 100% quality
[data2 writeToFile:jpegFilePath atomically:YES];
NSLog(#"saving image done");
[image release];
>> Update Additional:
You need to save image name(unique name that you can do early..right..!!) in sqlite database and you can make path or retrieve image using that name as i shown below.
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *getImagePath = [documentsDirectory stringByAppendingPathComponent:#"test.png"];// here you jus need to pass image name that you entered when you stored it.
Hope, this will help you...
After implementing #Nit's code.. you can refer This for insert record in database.
This is showing how to insert record in DB. and for getting path read my comments in #Nit's answer.
UPDATE:
For getting path of each downloaded file you have to keep unique name for each file. Now you will have the path where you are writing file that is unique path for every file. Now you simply need to execute insert query every time you download a file or need to save filepath in array and execute query later according to your requirement. Don't forget to give different file name to every file otherwise only single file will be there and your path will be same.
For getting unique filename you can use timestamp:
NSString *fileName = [NSString stringWithFormat:#"%lf.png", [[NSDate date] timeIntervalSince1970];
UPDATE2:
You have path now like: /Users/John/Library/Application Support/iPhone Simulator/5.1/Applications/84A837AA-7881-4D99-B6E2-623DC9A2E5D3/Documents/test.png
For getting Image in Image view:
UIImage *img = [UIImage imageWithContentsOfFile:yourPath];
//[UIImage imageWithData:[NSData dataWithContentsOfFile:yourPath]];
UIImageView *imgView = // Alloc + Init + Setting frame etc
imgView.image = img;
This will show image in your imageview
Hope this helps
I am new to this and have searched a lot this week. I am trying to set a background image from a file I have downloaded from a url. I need to save the image for later. Specially if I am not connected to the internet I can still show this image.
I have validated by printing out the contents of the directory that the file exists. This is one of many code that I have tried to make the image appear in the background.
nNSString *docDir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *documentPath = [docDir stringByAppendingFormat:#"/mainback.png"];
// If you go to the folder below, you will find those pictures
NSLog(#"%#",documentPath);
if ([[NSFileManager defaultManager]fileExistsAtPath:documentPath]) {
NSData *data = [NSData dataWithContentsOfFile:documentPath];
UIImage *image = [[UIImage alloc] initWithData:data];
NSLog(#"WHAT - %f,%f",image.size.width,image.size.height);
UIColor *background = [[UIColor alloc] initWithPatternImage:[UIImage imageNamed:documentPath]];
self.view.backgroundColor = background;
[background release];
}
The code finds the image in the directory but I cannot set the image to the background. Please help.
Thanks
Use a UIImageView (Apple documentation linked) instead of doing what you are trying to do with UIColor.
It'll be a lot more straightforward and less problematic.
I'm using a UITableView to show 2 to 3 images as thumbnail in each table view cell. The images which I'm showing it in the tableview are huge in size. If I'm using those images directly without any size reduction then the tableview may lose some images if I move back and forth between TableView and other view controllers.
So, I thought of size reduction code which reduces the size of the images. The code given below works great and the previous issue was fixed. But the tableview looses its smooth scrolling because the size reduction code uses a lot of memory. Every time when a new tableview cell is shown, it processes (reduces the size) the images in the particular tableview cell.
There may be a simple solution for this. Thanks in Advance.
//Size Reduction Code
CGSize newSize=CGSizeMake(_new_width, _new_height);
UIGraphicsBeginImageContext( newSize );
[sd._image drawInRect:CGRectMake(0,0,newSize.width,newSize.height)];
UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
scene_image_preview.image =newImage;
On top of reducing the image you can store the resulting newImage as a file in the documents folder of your app.
NSData *imageData = UIImagePNGRepresentation([UIImage imageWithCGImage:newImage]);
CGImageRelease(newImage);
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *path = [NSString stringWithFormat:#"%#/%#%d_%d.png",documentsDirectory, prefix, x, y];
[imageData writeToFile:path atomically:NO];
Depending on how many images you have, you can just keep all the reduced-size images in an NSMutableDictionary that's a property of your class.
In other words:
In your header
#property (nonatomic, retain) NSMutableDictionary *sizedImages;
Then in your cellForRowAtIndexPath: code
UIImage *sizedImage = [sizedImages objectForKey:[NSNumber numberWithInt:indexPath.row]];
//Or you could use the filename as the key
if (!sizedImage) {
sizedImage = [self sizeImage];(your sizing method)
[sizedImages setObject:sizedImage forKey:[NSNumber numberWithInt:indexPath.row]];
}
A few possible options
Perform the resizing in the background so it doesn't hold up the main thread.
Cache the resized image after doing it so there is only a delay the first time (this could be used in conjunction with doing it in the background so there is no delay on the scrolling)
Are you downloading the images? If so, download a thumbnail first and display that. Then if the image is selected, display the thumbnail scaled up to full screen which will look blocky, but then download the full-size image in the background and display that when it has loaded.
If you aren't downloading the images, but they are included in the app, just include thumbnails as well and display them instead
drawing images usually takes time.i think you can try to place the images in imageView by giving the frame sizes as desired.i doesn't make difference in look of the images.
add the imageviews to the cell and add the images to the imageView
These two links are very useful
http://www.fieryrobot.com/blog/2008/10/01/glassy-scrolling-with-uitableview/
and his follow up post
http://www.fieryrobot.com/blog/2008/10/08/more-glassy-scrolling-with-uitableview/
The first link is a few best practices. The second link will eb more useful to you; render your whole table view cell to an image and use that instead - this can be cached to disk to free memory & can be used between runs of the app.
- (void)saveImage:(UIImage *)image withName:(NSString *)name {
[myArray addObject:name];
//save image
NSData *data = UIImageJPEGRepresentation(image, 1.0);
NSFileManager *fileManager = [NSFileManager defaultManager];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *fullPath = [documentsDirectory stringByAppendingPathComponent:name];
[fileManager createFileAtPath:fullPath contents:data attributes:nil];
}
- (UIImage *)loadImage:(NSString *)name {
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *fullPath = [documentsDirectory stringByAppendingPathComponent:name];
UIImage *res = [UIImage imageWithContentsOfFile:fullPath];
return res;
}
Finally, I got a solution to load number of large sized images simultaneously. First, I reduced the size of the image using the size reduction code above and I saved those sized images to documents directory for the first time and then I loaded the saved images from the documents directory using these saveImage and loadImage functions.
Thanks for all the comments and suggestions to solve this.
I am attempting to save and load a UIImage to and from the iPhone documents directory after the image is picked from the iPhone Photo Library. It is able to do so, but for some reason, when I load the image, it rotates it 90 degrees counterclockwise. Here is my saveImage and loadImage methods:
Save Image:
- (void)saveImage: (UIImage*)image{
if (image != nil)
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString* path = [documentsDirectory stringByAppendingPathComponent:
[NSString stringWithString: #"lePhoto.png"] ];
//NSData* data = UIImagePNGRepresentation(image);
//[data writeToFile:path atomically:YES];
[UIImagePNGRepresentation(image) writeToFile:path atomically:YES];
}
}
Load Image:
- (NSData*)loadImage{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString* path = [documentsDirectory stringByAppendingPathComponent:
[NSString stringWithString: #"lePhoto.png"] ];
NSData *data = [[NSData alloc] initWithContentsOfFile:path];
//UIImage *image = [[UIImage alloc] initWithData:data]; //my second try
//UIImage* image = [UIImage imageWithContentsOfFile:path]; //first try
//return image;
return data;
[data release];
}
And I am now loading the image like this, to see if it would, for some crazy reason, solve my problem (it didn't, obviously):
UIImage* theImage = [[UIImage alloc] initWithData:[self loadImage]];
I have done some testing where I have two UIImageViews side-by-side, one on the left that doesn't save and load the image before display (it just straight-up shows the image once a photo is picked from the ImagePicker), and one on the right that displays AFTER the save load occurs. The one on the right is the only one rotating 90 degrees CCW; the non Save/Load picture is displaying correctly. This only occurs on the actual iPhone. The simulator shows both images correctly. I have spent many, many hours attempting to figure it out, but to no avail. Any ideas as to what could be causing this?
EDIT: It should also be known that the image always says it's oriented up, even when it obviously isn't! It only rotates after ALL of the code has been run. I've tried doing a force redraw in between my code to see if that changes things, but it doesn't (though it is possible I'm even doing that wrong. Who knows, anymore).
Also, it will not autorotate photos that have been screenshot from the iPhone. Only photos that have been taken by the camera. [I haven't tried downloaded photos.] It's the weirdest thing...
And if you're wondering exactly how I'm pulling my picture, here's the method that will at least shed light on what I'm doing (it's not every method needed to do this function, obviously, but it gives insight on how I've written my code):
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
theimageView.image = [info objectForKey:#"UIImagePickerControllerOriginalImage"];
[self saveImage:[info objectForKey:#"UIImagePickerControllerOriginalImage"]];
[picker dismissModalViewControllerAnimated:YES];
}
Any advice is greatly appreciated. And I do know this much: if there's a way to do something crazy to get some stupid, never-before-heard-of problem, chances are, I'll find it, apparently :P
Ok. I figured it out. Apparently when you save things with PNG representation, and not JPEG representation, the image orientation information is not saved with it. Because of this, every image loaded will default to showing orientation up. So, the easiest way is to do this:
NSData* data = UIImageJPEGRepresentation(image,0.0);
[data writeToFile:path atomically:YES];
instead of this:
[UIImagePNGRepresentation(image) writeToFile:path atomically:YES];
And, of course, changing all the picture names from .png to .jpg. The 0.0 part of the code above is to control Alpha levels, which is required of jpegs. Hope this helps people in the future!
I assume you're using the Assets Library Framework to get the image. If so, you'll want to get the orientation of the image in your results block, and manipulate the UIImage to adjust. I have something like the following:
ALAssetsLibraryAssetForURLResultBlock resultBlock = ^(ALAsset* asset)
{
ALAssetRepresentation* rep = [asset defaultRepresentation];
_orientation = rep.orientation;
...
}
Aside: What a great type name, huh? Holy moly, does Objective-C need namespaces!
Thanks so much...
This code has worked and saved several hours of work for me.
NSData* data = UIImageJPEGRepresentation(image,0.0);
[data writeToFile:path atomically:YES];
in the place of
[UIImagePNGRepresentation(image) writeToFile:path atomically:YES];