【发布时间】:2015-07-23 23:34:15
【问题描述】:
我这里有这个方法,它可以将我的 UIWebView 转换为 PDF 并且效果很好。但是当我打印出这个 PDF 或通过电子邮件发送它时,它被切断了。它就像它只生成我设置的 UIWebView 的大小(宽度:688 和高度:577)如果我将 UIWebView 的大小增加到 900 或 1024,我的 PDF 是空的。我的 UIWebView 大于 577,但在我的应用程序中,我可以滚动。
这里是方法....
-(void)webViewDidFinishLoad:(UIWebView *)webViewPDF
{
CGRect origframe = webViewPDF.frame;
NSString *heightStr = [webViewPDF stringByEvaluatingJavaScriptFromString:@"document.body.scrollHeight;"]; // Get the height of our webView
int height = [heightStr intValue];
CGFloat maxHeight = kDefaultPageHeight - 2*kMargin;
int pages = floor(height / maxHeight);
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *path = [paths objectAtIndex:0];
self.pdfPath = [path stringByAppendingPathComponent:[NSString stringWithFormat:@"Purchase Order.pdf"]];
UIGraphicsBeginPDFContextToFile(self.pdfPath, CGRectZero, nil);
for (int i = 0; i < pages; i++)
{
if (maxHeight * (i+1) > height) {
CGRect f = [webViewPDF frame];
f.size.height -= (((i+1) * maxHeight) - height);
[webViewPDF setFrame: f];
}
UIGraphicsBeginPDFPageWithInfo(CGRectMake(0, 0, kDefaultPageWidth, kDefaultPageHeight), nil);
CGContextRef currentContext = UIGraphicsGetCurrentContext();
CGContextTranslateCTM(currentContext, kMargin, kMargin);
[webViewPDF.layer renderInContext:currentContext];
}
UIGraphicsEndPDFContext();
[webViewPDF setFrame:origframe];
[[[webViewPDF subviews] lastObject] setContentOffset:CGPointMake(0, 0) animated:NO];
}
我希望这是有道理的....有没有人对如何解决这个问题有任何建议,所以 PDF 不会被切断?
我忘了提到这些变量:
#define kDefaultPageHeight 850
#define kDefaultPageWidth 850
#define kMargin 50
这是我的分享按钮:
- (IBAction)Share:(id)sender {
NSData *pdfData = [NSData dataWithContentsOfFile:self.pdfPath];
UIActivityViewController * activityController = [[UIActivityViewController alloc] initWithActivityItems:@[pdfData] applicationActivities:nil];
UIPopoverController *popup = [[UIPopoverController alloc] initWithContentViewController:activityController];
[popup presentPopoverFromRect:CGRectMake(self.view.frame.size.width - 36, 60, 0, 0)inView:self.view permittedArrowDirections:UIPopoverArrowDirectionUp animated:YES];
}
【问题讨论】:
-
那么这和Objective-C有什么关系呢?
-
这个方法是Objective-C
-
显然您的代码恰好在 Objective-C 中。任何人都可以看到这一点。但问题不在于关于 Objective-C。无论您使用的是 Objective-C、Swift、AppleScript 还是其他任何东西,答案都是一样的。
-
您是否尝试过将 UIWebview 的边界设置为 PDF 中页面的大小,然后滚动 UIWebview 以便在调用 layer.renderInContext 之前显示该页面所需的确切片段? UIWebview 可能会优化绘图,使其仅将在任何给定时间可见的内容部分绘制到其图层。
-
我不明白@DavidvanDriessche,你能回答一下吗?
标签: ios objective-c pdf uiwebview