【发布时间】:2011-01-28 02:23:04
【问题描述】:
有没有办法获取UIWebView 的内容并将其转换为PDF 或PNG 文件?例如,我想通过在从 Safari 打印时选择 PDF 按钮来获得与 Mac 上可用的输出类似的输出。我假设这是不可能的/内置的,但希望我会感到惊讶并找到一种将内容从 web 视图获取到文件的方法。
谢谢!
【问题讨论】:
标签: iphone objective-c cocoa-touch pdf png
有没有办法获取UIWebView 的内容并将其转换为PDF 或PNG 文件?例如,我想通过在从 Safari 打印时选择 PDF 按钮来获得与 Mac 上可用的输出类似的输出。我假设这是不可能的/内置的,但希望我会感到惊讶并找到一种将内容从 web 视图获取到文件的方法。
谢谢!
【问题讨论】:
标签: iphone objective-c cocoa-touch pdf png
您可以在 UIView 上使用以下类别来创建 PDF 文件:
#import <QuartzCore/QuartzCore.h>
@implementation UIView(PDFWritingAdditions)
- (void)renderInPDFFile:(NSString*)path
{
CGRect mediaBox = self.bounds;
CGContextRef ctx = CGPDFContextCreateWithURL((CFURLRef)[NSURL fileURLWithPath:path], &mediaBox, NULL);
CGPDFContextBeginPage(ctx, NULL);
CGContextScaleCTM(ctx, 1, -1);
CGContextTranslateCTM(ctx, 0, -mediaBox.size.height);
[self.layer renderInContext:ctx];
CGPDFContextEndPage(ctx);
CFRelease(ctx);
}
@end
坏消息:UIWebView 不会在 PDF 中创建漂亮的形状和文本,而是将自身呈现为 PDF 中的图像。
【讨论】:
从 Web 视图创建图像很简单:
UIImage* image = nil;
UIGraphicsBeginImageContext(offscreenWebView_.frame.size);
{
[offscreenWebView_.layer renderInContext: UIGraphicsGetCurrentContext()];
image = UIGraphicsGetImageFromCurrentImageContext();
}
UIGraphicsEndImageContext();
获得图像后,您可以将其保存为 PNG。
也可以以非常相似的方式创建 PDF,但仅限于尚未发布的 iPhone OS 版本。
【讨论】:
@mjdth,试试fileURLWithPath:isDirectory:。 URLWithString 也不适合我。
@implementation UIView(PDFWritingAdditions)
- (void)renderInPDFFile:(NSString*)path
{
CGRect mediaBox = self.bounds;
CGContextRef ctx = CGPDFContextCreateWithURL((CFURLRef)[NSURL fileURLWithPath:path isDirectory:NO], &mediaBox, NULL);
CGPDFContextBeginPage(ctx, NULL);
CGContextScaleCTM(ctx, 1, -1);
CGContextTranslateCTM(ctx, 0, -mediaBox.size.height);
[self.layer renderInContext:ctx];
CGPDFContextEndPage(ctx);
CFRelease(ctx);
}
@end
【讨论】:
下面的代码会将 UIWebView 的(完整)内容转换为 UIImage。
渲染 UIImage 后,我将其以 PNG 格式写入磁盘以查看结果。
当然,你可以随心所欲地使用 UIImage。
UIImage *image = nil;
CGRect oldFrame = webView.frame;
// Resize the UIWebView, contentSize could be > visible size
[webView sizeToFit];
CGSize fullSize = webView.scrollView.contentSize;
// Render the layer content onto the image
UIGraphicsBeginImageContext(fullSize);
CGContextRef resizedContext = UIGraphicsGetCurrentContext();
[webView.layer renderInContext:resizedContext];
image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
// Revert the UIWebView back to its old size
webView.frame = oldFrame;
// Write the UIImage to disk as PNG so that we can see the result
NSString *path= [NSHomeDirectory() stringByAppendingPathComponent:@"Documents/Test.png"];
[UIImagePNGRepresentation(image) writeToFile:path atomically:YES];
注意:确保 UIWebView 已完全加载(UIWebViewDelegate 或 loading 属性)。
【讨论】: