UIWebView全部区域截图保存为UIImage或者PDF
2017-07-05 本文已影响70人
捏捏你的脸
公司项目需求,需要生成电子合同表单。用WebView显示加载出来。故写个UIWebView扩展,代码如下。
//
// UIWebView+MMWebViewExtention.h
// yuxi-manager
//
// Created by Sven on 2017/7/5.
// Copyright © 2017年 ylink. All rights reserved.
//
#import <UIKit/UIKit.h>
@interface UIWebView (MMWebViewExtention)
/**
将整个webView转换成一张图片
@return webView的图片
*/
- (UIImage *)imageRepresentation;
/**
将整个webView转换成一个PDF的文件
@return pdfData
*/
- (NSData *)PDFData;
@end
//
// UIWebView+MMWebViewExtention.m
// yuxi-manager
//
// Created by Sven on 2017/7/5.
// Copyright © 2017年 ylink. All rights reserved.
//
#import "UIWebView+MMWebViewExtention.h"
#import <QuartzCore/QuartzCore.h>
@implementation UIWebView (MMWebViewExtention)
- (UIImage *)imageRepresentation{
CGFloat scale = [UIScreen mainScreen].scale;
CGSize boundsSize = self.bounds.size;
CGFloat boundsWidth = boundsSize.width;
CGFloat boundsHeight = boundsSize.height;
CGSize contentSize = self.scrollView.contentSize;
CGFloat contentHeight = contentSize.height;
CGPoint offset = self.scrollView.contentOffset;
[self.scrollView setContentOffset:CGPointMake(0, 0)];
NSMutableArray *images = [NSMutableArray array];
while (contentHeight > 0) {
UIGraphicsBeginImageContextWithOptions(boundsSize, NO, 0.0);
[self.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
[images addObject:image];
CGFloat offsetY = self.scrollView.contentOffset.y;
[self.scrollView setContentOffset:CGPointMake(0, offsetY + boundsHeight)];
contentHeight -= boundsHeight;
}
[self.scrollView setContentOffset:offset];
CGSize imageSize = CGSizeMake(contentSize.width * scale,
contentSize.height * scale);
UIGraphicsBeginImageContext(imageSize);
[images enumerateObjectsUsingBlock:^(UIImage *image, NSUInteger idx, BOOL *stop) {
[image drawInRect:CGRectMake(0,
scale * boundsHeight * idx,
scale * boundsWidth,
scale * boundsHeight)];
}];
UIImage *fullImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return fullImage;
}
- (NSData *)PDFData{
UIViewPrintFormatter *fmt = [self viewPrintFormatter];
UIPrintPageRenderer *render = [[UIPrintPageRenderer alloc] init];
[render addPrintFormatter:fmt startingAtPageAtIndex:0];
CGRect page;
page.origin.x=0;
page.origin.y=0;
page.size.width=600;
page.size.height=768;
CGRect printable=CGRectInset( page, 50, 50 );
[render setValue:[NSValue valueWithCGRect:page] forKey:@"paperRect"];
[render setValue:[NSValue valueWithCGRect:printable] forKey:@"printableRect"];
NSMutableData * pdfData = [NSMutableData data];
UIGraphicsBeginPDFContextToData( pdfData, CGRectZero, nil );
for (NSInteger i=0; i < [render numberOfPages]; i++)
{
UIGraphicsBeginPDFPage();
CGRect bounds = UIGraphicsGetPDFContextBounds();
[render drawPageAtIndex:i inRect:bounds];
}
UIGraphicsEndPDFContext();
return pdfData;
}
@end
很舒服,代码直接拷贝可用~ 如果您喜欢 ,请给个赞!