mjd*_*dth 16 pdf iphone png cocoa-touch objective-c
有没有办法获取a的内容UIWebView
并将其转换为PDF或PNG文件?例如,我希望通过从Safari打印时选择PDF按钮获得与Mac上可用的输出类似的输出.我假设这是不可能/内置的,但希望我会惊讶并找到一种方法将内容从webview获取到文件.
谢谢!
Nik*_*uhe 21
您可以在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
Run Code Online (Sandbox Code Playgroud)
坏消息:UIWebView不会在PDF中创建漂亮的形状和文本,而是将自身呈现为PDF中的图像.
从Web视图创建图像很简单:
UIImage* image = nil;
UIGraphicsBeginImageContext(offscreenWebView_.frame.size);
{
[offscreenWebView_.layer renderInContext: UIGraphicsGetCurrentContext()];
image = UIGraphicsGetImageFromCurrentImageContext();
}
UIGraphicsEndImageContext();
Run Code Online (Sandbox Code Playgroud)
获得图像后,您可以将其另存为PNG.
也可以以非常类似的方式创建PDF,但仅限于尚未发布的iPhone OS版本.