我希望我的WebView保存为任何格式的图像或pdf,
我尝试使用以下代码保存网页:
UIGraphicsBeginImageContext(WebPage.frame.size);
[WebPage.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage *viewImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
UIImageWriteToSavedPhotosAlbum(viewImage, nil, nil, nil);
但是我得到的部分是可见的..
我想知道如何获取整个网页图片或苹果人如何进行空气打印以便整个网页可以打印..我不想知道“AirPrint功能”我想知道如何使用iPhone获取网页图片..
因为我对iOS开发更新鲜。
任何人都可以帮我处理保存网页的代码吗?
答案 0 :(得分:2)
- (IBAction)printSaveTheWebView:(id)sender
{
UIImage *viewImage;
UIScrollView *Scroll_view = webView.scrollView;
CGRect savedFrame;
UIGraphicsBeginImageContext(Scroll_view.contentSize);
{
CGPoint savedContentOffset = Scroll_view.contentOffset;
savedFrame = Scroll_view.frame;
Scroll_view.contentOffset = CGPointZero;
Scroll_view.frame = CGRectMake(0, 0, Scroll_view.contentSize.width, Scroll_view.contentSize.height);
[Scroll_view.layer renderInContext: UIGraphicsGetCurrentContext()];
viewImage = UIGraphicsGetImageFromCurrentImageContext();
Scroll_view.contentOffset = savedContentOffset;
Scroll_view.frame = savedFrame;
}
UIGraphicsEndImageContext();
UIImageWriteToSavedPhotosAlbum(viewImage, self, nil, nil);
[UIImagePNGRepresentation(viewImage) writeToFile:[NSHomeDirectory() stringByAppendingPathComponent:@"view.png"] atomically:YES];
}
点击按钮时调用此方法
答案 1 :(得分:2)
- (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;
}
}
答案 2 :(得分:1)
要获得您的要求,您必须通过更改框架来更改context
的{{1}},为此需要一个for循环并通过更改上下文根据页数循环它。< / p>