我的应用程序接收 UIWebView 的内容并生成网页的 PDF。这在较小的页面上工作正常,但是当它达到大约 10 页时,它会崩溃“由于内存压力”。此外,这是一个 ARC 应用程序。
我看到的主要答案是使用UIGraphicsBeginPDFContextToFile
而不是使用,UIGraphicsBeginPDFContextToData
并且在更改为使用之后,File
我仍然会遇到内存压力崩溃。我不明白为什么它没有从内存中清除页面。我还@autoreleasepool { ... }
按照另一个问题中的建议添加了循环中的内容。关于我在这里做错了什么的任何想法?
这是PDF创建代码:
UIGraphicsBeginPDFContextToFile(dataFile, CGRectZero, nil);
for (int i = 0; i < pages; i++) {
@autoreleasepool {
NSLog(@"Creating Page %i", i);
// Check to see if page draws more than the height of the UIWebView
if ((i+1) * 720 > height) {
CGRect f = [_appWebView frame];
f.size.height -= (((i+1) * 720.0) - height);
[_appWebView setFrame: f];
}
UIGraphicsBeginPDFPage();
CGContextRef currentContext = UIGraphicsGetCurrentContext();
CGContextTranslateCTM(currentContext, 36, 36); // Translate for 0.5" margins
[[[_appWebView subviews] lastObject] setContentOffset:CGPointMake(0, 720 * i) animated:NO];
[_appWebView.layer renderInContext:currentContext];
}
}
UIGraphicsEndPDFContext();
如果有帮助,这是完整的方法:
-(void) generatePDF {
startingFrame = _appWebView.frame;
// Memory warning seems to happen on almost every PDF, clear cache here to be proactive.
[[NSURLCache sharedURLCache] removeAllCachedResponses];
UIWebView *webView = [[UIWebView alloc] initWithFrame: CGRectMake(0, 0, 6.5 * 72, 9 * 72)];
[webView setDelegate: self];
// Adjust to letter size paper size in portrait mode
CGRect frame = _appWebView.frame;
frame.size.height = 10*72; // 11" - 1" Margins = 720px (72px / inch)
frame.size.width = 7.5*72; // 8.5 - 1" Margins = 612px (72px / inch)
_appWebView.frame = frame;
[_appWebView stringByEvaluatingJavaScriptFromString:@"window.scroll(0, 0);"];
// Get the height of our webView
NSString *heightStr = [_appWebView stringByEvaluatingJavaScriptFromString:@"document.body.scrollHeight;"];
int height = [heightStr intValue];
// Get the number of pages needed to print. 10 * 72 = 720
int pages = ceil(height / 720.0);
// File
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *dataFile = [documentsDirectory stringByAppendingPathComponent:@"Configuration.pdf"];
NSLog(@"File: %@", dataFile);
UIGraphicsBeginPDFContextToFile(dataFile, CGRectZero, nil);
for (int i = 0; i < pages; i++) {
@autoreleasepool {
NSLog(@"Creating Page %i", i);
// Check to see if page draws more than the height of the UIWebView
if ((i+1) * 720 > height) {
CGRect f = [_appWebView frame];
f.size.height -= (((i+1) * 720.0) - height);
[_appWebView setFrame: f];
}
UIGraphicsBeginPDFPage();
CGContextRef currentContext = UIGraphicsGetCurrentContext();
CGContextTranslateCTM(currentContext, 36, 36); // Translate for 0.5" margins
[[[_appWebView subviews] lastObject] setContentOffset:CGPointMake(0, 720 * i) animated:NO];
[_appWebView.layer renderInContext:currentContext];
}
}
UIGraphicsEndPDFContext();
// Adjust to original size
_appWebView.frame = startingFrame;
}