#import <WebKit/WebKit.h>
@interface WKWebView (toFile)
- (UIImage *)imageRepresentation;
- (NSData *)PDFData;
@end
#import "WKWebView+toFile.h"
#import <QuartzCore/QuartzCore.h>
@implementation WKWebView (toFile)
- (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
iOS【WKWebView转PDF、图片】
©著作权归作者所有,转载或内容合作请联系作者
- 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
- 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
- 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
推荐阅读更多精彩内容
- 网络里有各种高大上的报告,但是不好找到PDF或PPT版本,收集了很多JPG图片,又不适合分发,这个时候就需要用到J...