Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get a PDF/PNG as output from a UIWebView or UIView

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 selecting the PDF button when printing from Safari, for example. I'm assuming this isn't possible/built in yet, but hopefully I'll be surprised and find a way to get the content from a webview to a file.

Thanks!

like image 914
mjdth Avatar asked Mar 16 '10 12:03

mjdth


2 Answers

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.

like image 102
Nikolai Ruhe Avatar answered Sep 18 '22 19:09

Nikolai Ruhe


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.

like image 36
Stefan Arentz Avatar answered Sep 19 '22 19:09

Stefan Arentz