Search code examples
iphoneiosobjective-cios5ios4

Printing and saving a web page Using iPhone


I want my WebView to save as image or pdf of any formate,

I tried with saving the web page using the code :

   UIGraphicsBeginImageContext(WebPage.frame.size);
   [WebPage.layer renderInContext:UIGraphicsGetCurrentContext()];
   UIImage *viewImage = UIGraphicsGetImageFromCurrentImageContext();
   UIGraphicsEndImageContext();
   UIImageWriteToSavedPhotosAlbum(viewImage, nil, nil, nil);

but i'm getting the part which is visible..

i want to know how to get the entire web page image or how the apple people giving the air print so that the entire web page can b printed.. i dont want to know the "AirPrint function" i want to know how to get web page image using the iPhone..

As i'm fresher to iOS development.

can any one help me with he working code of saving web page?


Solution

  • - (void)printAndSave
    {
        webViewHeight = [[self.myWebView stringByEvaluatingJavaScriptFromString:@"document.body.scrollHeight;"] integerValue];
        CGRect screenRect = self.myWebView.frame;
        double currentWebViewHeight = webViewHeight;
        while (currentWebViewHeight > 0)
        {
            imageName ++;
            UIGraphicsBeginImageContext(screenRect.size);
            CGContextRef ctx = UIGraphicsGetCurrentContext();
            [[UIColor blackColor] set];
            CGContextFillRect(ctx, screenRect);
            [self.myWebView.layer renderInContext:ctx];
            UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
            UIGraphicsEndImageContext();
            NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
            NSString *documentsDirectory = [paths objectAtIndex:0];
            NSString *pngPath = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:@"%d.png",imageName]];
            if(currentWebViewHeight < 460)
            {
                CGRect lastImageRect = CGRectMake(0, 457 - currentWebViewHeight, self.myWebView.frame.size.width, currentWebViewHeight);
                CGImageRef lastImageRef = CGImageCreateWithImageInRect([newImage CGImage], lastImageRect);
                newImage = [UIImage imageWithCGImage:lastImageRef];
                CGImageRelease(lastImageRef);
            }
            [UIImagePNGRepresentation(newImage) writeToFile:pngPath atomically:YES];
            [self.myWebView stringByEvaluatingJavaScriptFromString:@"window.scrollBy(0,460);"];
            currentWebViewHeight -= 460;
        }
    }