繁体   English   中英

从UIWebView或UIView获取PDF / PNG作为输出

[英]Get a PDF/PNG as output from a UIWebView or UIView

有没有办法获取UIWebView的内容并将其转换为PDF或PNG文件? 例如,我希望通过从Safari打印时选择PDF按钮获得与Mac上可用的输出类似的输出。 我认为这是不可能的/内置的,但希望我会惊讶并找到一种方法将内容从webview获取到文件。

谢谢!

您可以在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版本。

下面的代码将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或加载属性)。

@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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM