代码之家  ›  专栏  ›  技术社区  ›  mjdth

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

  •  16
  • mjdth  · 技术社区  · 16 年前

    有什么方法可以得到 UIWebView

    4 回复  |  直到 16 年前
        1
  •  21
  •   Nikolai Ruhe    16 年前

    可以使用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中。

        2
  •  5
  •   Stefan Arentz    16 年前

    从web视图创建图像很简单:

    UIImage* image = nil;
    
    UIGraphicsBeginImageContext(offscreenWebView_.frame.size);
    {
        [offscreenWebView_.layer renderInContext: UIGraphicsGetCurrentContext()];
        image = UIGraphicsGetImageFromCurrentImageContext();
    }
    UIGraphicsEndImageContext();
    

    一旦你有了图像,你可以保存为PNG格式。

    创建PDF也可以用非常类似的方式实现,但只能在尚未发布的iPhone OS版本上实现。

        3
  •  0
  •   Ford    16 年前

    @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
    
        4
  •  0
  •   Yvo    13 年前

    下面的代码将UIWebView的(完整)内容转换为UIImage。

    渲染完UIImage后,我将其作为PNG写入磁盘以查看结果。

    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属性)。