Is there any way to get the content of a UIWebView
and convert it to a PDF or PNG file? I\'d like to get similar output to that available on the Mac by selectin
@mjdth, try fileURLWithPath:isDirectory:
instead. URLWithString
wasn't working for me either.
@implementation UIView(PDFWritingAdditions)
- (void)renderInPDFFile:(NSString*)path
{
CGRect mediaBox = self.bounds;
CGContextRef ctx = CGPDFContextCreateWithURL((CFURLRef)[NSURL fileURLWithPath:path isDirectory:NO], &mediaBox, NULL);
CGPDFContextBeginPage(ctx, NULL);
CGContextScaleCTM(ctx, 1, -1);
CGContextTranslateCTM(ctx, 0, -mediaBox.size.height);
[self.layer renderInContext:ctx];
CGPDFContextEndPage(ctx);
CFRelease(ctx);
}
@end
The code below will convert the (full) content of a UIWebView to an UIImage.
After rendering the UIImage I write it to disk as PNG to see the result.
Of course you could do with the UIImage whatever you like.
UIImage *image = nil;
CGRect oldFrame = webView.frame;
// Resize the UIWebView, contentSize could be > visible size
[webView sizeToFit];
CGSize fullSize = webView.scrollView.contentSize;
// Render the layer content onto the image
UIGraphicsBeginImageContext(fullSize);
CGContextRef resizedContext = UIGraphicsGetCurrentContext();
[webView.layer renderInContext:resizedContext];
image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
// Revert the UIWebView back to its old size
webView.frame = oldFrame;
// Write the UIImage to disk as PNG so that we can see the result
NSString *path= [NSHomeDirectory() stringByAppendingPathComponent:@"Documents/Test.png"];
[UIImagePNGRepresentation(image) writeToFile:path atomically:YES];
Note: make sure the UIWebView is fully loaded (UIWebViewDelegate or loading property).
Creating a image from a web view is simple:
UIImage* image = nil;
UIGraphicsBeginImageContext(offscreenWebView_.frame.size);
{
[offscreenWebView_.layer renderInContext: UIGraphicsGetCurrentContext()];
image = UIGraphicsGetImageFromCurrentImageContext();
}
UIGraphicsEndImageContext();
Once you have the image you can save it as a PNG.
Creating PDFs is also possible in a very similar way, but only on a yet unreleased iPhone OS version.
You can use the following category on UIView to create a PDF file:
#import <QuartzCore/QuartzCore.h>
@implementation UIView(PDFWritingAdditions)
- (void)renderInPDFFile:(NSString*)path
{
CGRect mediaBox = self.bounds;
CGContextRef ctx = CGPDFContextCreateWithURL((CFURLRef)[NSURL fileURLWithPath:path], &mediaBox, NULL);
CGPDFContextBeginPage(ctx, NULL);
CGContextScaleCTM(ctx, 1, -1);
CGContextTranslateCTM(ctx, 0, -mediaBox.size.height);
[self.layer renderInContext:ctx];
CGPDFContextEndPage(ctx);
CFRelease(ctx);
}
@end
Bad news: UIWebView does not create nice shapes and text in the PDF, but renders itself as an image into the PDF.