我花了很多时间在谷歌搜索,但我没有取得好成绩。 我将UIWebView转换为PDF,这是一个带有长内容的webview(webview中滚动的ContentSize)。
我使用了RenderInContext for循环,但是当我使用webview转换时它会崩溃 请帮我修复20页错误。
这是我的代码:
UIGraphicsBeginPDFContextToFile(documentDirectoryFilename, CGRectMake(0, 0, aWebView.scrollView.contentSize.width, screenHight), nil);
aWebView.scrollView.contentSize.width, screenHight), nil);
for (int i = 0; i < 20; i++) {
@autoreleasepool {
UIGraphicsBeginPDFPage();
CGContextRef currentContext = UIGraphicsGetCurrentContext();
[[[aWebView subviews] lastObject] setContentOffset:CGPointMake(0, screenHight * i) animated:NO];
[aWebView.layer renderInContext:currentContext];
currentContext = nil;
}
}
UIGraphicsEndPDFContext();
aWebView.layer.contents = nil;
我使用了autoReleasePool并将结果保存到文件中。但它也会导致崩溃。
答案 0 :(得分:0)
尝试以下使用的测试代码,对我来说很合适......
-(void)createPDFfromUIView:(UIWebView*)webView saveToDocumentsWithFileName:(NSString*)aFilename
{
NSString *heightStr = [webView stringByEvaluatingJavaScriptFromString:@"document.body.scrollHeight;"];
int height = [heightStr intValue];
// CGRect screenRect = [[UIScreen mainScreen] bounds];
// CGFloat screenHeight = (self.contentWebView.hidden)?screenRect.size.width:screenRect.size.height;
CGFloat screenHeight = webView.bounds.size.height;
int pages = ceil(height / screenHeight);
NSMutableData *pdfData = [NSMutableData data];
UIGraphicsBeginPDFContextToData(pdfData, webView.bounds, nil);
CGRect frame = [webView frame];
for (int i = 0; i < pages; i++) {
// Check to screenHeight if page draws more than the height of the UIWebView
if ((i+1) * screenHeight > height) {
CGRect f = [webView frame];
f.size.height -= (((i+1) * screenHeight) - height);
[webView setFrame: f];
}
UIGraphicsBeginPDFPage();
CGContextRef currentContext = UIGraphicsGetCurrentContext();
// CGContextTranslateCTM(currentContext, 72, 72); // Translate for 1" margins
[[[webView subviews] lastObject] setContentOffset:CGPointMake(0, screenHeight * i) animated:NO];
[webView.layer renderInContext:currentContext];
}
UIGraphicsEndPDFContext();
// Retrieves the document directories from the iOS device
NSArray* documentDirectories = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask,YES);
NSString* documentDirectory = [documentDirectories objectAtIndex:0];
NSString* documentDirectoryFilename = [documentDirectory stringByAppendingPathComponent:aFilename];
// instructs the mutable data object to write its context to a file on disk
[pdfData writeToFile:documentDirectoryFilename atomically:YES];
[webView setFrame:frame];
}