2010-03-16 9 views
16

¿Hay alguna manera de obtener el contenido de un UIWebView y convertirlo a un archivo PDF o PNG? Me gustaría obtener un resultado similar al disponible en la Mac seleccionando el botón PDF al imprimir desde Safari, por ejemplo. Supongo que aún no es posible/incorporado, pero con suerte me sorprenderé y encontraré una manera de llevar el contenido de una vista web a un archivo.Obtenga un PDF/PNG como salida de un UIWebView o UIView

Gracias!

Respuesta

21

Usted puede usar la siguiente categoría en UIView para crear un archivo 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 

Malas noticias: UIWebView no crea buenas formas y texto en el PDF, sino que hace a sí misma como una imagen en el formato PDF.

+0

Gracias por la publicación. Me está dando un problema, aunque donde CGPDFContextCreateWithURL no está creando correctamente el contexto. He probado varias URL diferentes y no parece cambiar nada. ¿Algunas ideas? – mjdth

+0

Hubo un error en cómo se creó CFURLRef. Lo arreglé y debería funcionar ahora para las URL de archivo adecuadas. –

+0

La representación de UILabels con este método parece rasterizar el texto. Si quiere que su texto permanezca vectorizado, dibuje directamente en la capa como se describe aquí http://stackoverflow.com/questions/2209734/add-text-to-calayer –

5

Creación de una imagen a partir de una vista web es sencilla:

UIImage* image = nil; 

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

Una vez que tenga la imagen que se guarda como un archivo PNG.

La creación de archivos PDF también es posible de una manera muy similar, pero solo en una versión para iPhone OS aún no publicada.

+0

Creo que la API CGPDF ... existía a partir de iPhone OS 2.0. –

+0

Sí, pero pensé que representar una capa en un contexto PDF era algo nuevo. –

+0

Esta respuesta casi funciona también. El problema es el tamaño de los cambios de página entre páginas. ¿Hay alguna manera de determinar el tamaño del contenido en la vista web para que pueda crear un contexto de tamaño correcto? – mjdth

0

@mjdth, pruebe fileURLWithPath:isDirectory: en su lugar. URLWithString tampoco me funcionaba.

@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 
0

El siguiente código convertirá el contenido (completo) de un UIWebView en un UIImage.

Después de renderizar el UIImage, lo escribo en el disco como PNG para ver el resultado.
Por supuesto que podría hacer con el UIImage lo que quiera.

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]; 

Nota: asegúrese de que el UIWebView está totalmente cargado (UIWebViewDelegate o la propiedad de carga).

Cuestiones relacionadas