我通过读取 webView 的内部 HTML 内容和读取 AsciiString 来使用这两种方法,但是在这两种方法中,当我将其转换为 PDF 格式数据时,数据会被截断。请查看我的代码并告诉我我错在哪里。
-(NSData *)createPDFfromUIWebView:(UIWebView*)webView saveToDocumentsWithFileName:(NSString*)aFilename
{
// Creates a mutable data object for updating with binary data, like a byte array
[self removeFileByName];
// NSString *heightStr = [webView stringByEvaluatingJavaScriptFromString:@"document.body.scrollHeight;"];
// NSString *heightStr = [webView stringByEvaluatingJavaScriptFromString:@"document.body.innerHTML"];
// NSString *heightStr = [webView stringByEvaluatingJavaScriptFromString:@"document.documentElement.outerHTML"];
// NSString *heightStr = (NSString *)[webView stringByEvaluatingJavaScriptFromString:@"getParam();"];
// NSString *heightStr = (NSString *)[webView stringByEvaluatingJavaScriptFromString:@"document.documentElement.innerText;"];
// NSString *heightStr = [webView stringByEvaluatingJavaScriptFromString:@"document.all[0].innerHTML"];
NSURL *requestURL = [[self.webViewIphone request] URL];
NSError *error;
NSString *heightStr = [NSString stringWithContentsOfURL:requestURL
encoding:NSASCIIStringEncoding
error:&error];
debug(@"HTml string %@",heightStr);
int height = [heightStr length];
CGFloat screenHeight = webView.scrollView.contentSize.height;
debug(@"%f",screenHeight);
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];
NSData *dataTemp = [NSData dataWithContentsOfFile:documentDirectoryFilename];
return dataTemp;
}