Existe alguma maneira de obter o conteúdo de um UIWebView
e convertê-lo em um arquivo PDF ou PNG? Eu gostaria de obter um resultado semelhante ao disponível no Mac, selecionando o botão PDF ao imprimir a partir do Safari, por exemplo. Eu estou supondo que isso não é possível / construído ainda, mas espero ser surpreendido e encontrar uma maneira de obter o conteúdo de uma webview para um arquivo.
Obrigado!
Você pode usar a seguinte categoria no UIView para criar um arquivo PDF:
#import @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
Más notícias: o UIWebView não cria formas e textos agradáveis no PDF, mas se transforma em uma imagem no PDF.
Criar uma imagem a partir de uma visualização da Web é simples:
UIImage* image = nil; UIGraphicsBeginImageContext(offscreenWebView_.frame.size); { [offscreenWebView_.layer renderInContext: UIGraphicsGetCurrentContext()]; image = UIGraphicsGetImageFromCurrentImageContext(); } UIGraphicsEndImageContext();
Depois de ter a imagem, você pode salvá-la como PNG.
A criação de PDFs também é possível de maneira muito semelhante, mas apenas em uma versão ainda não lançada do iPhone OS.
@mjdth, tente fileURLWithPath:isDirectory:
vez disso. URLWithString
não estava funcionando para mim também.
@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
O código abaixo irá converter o conteúdo (completo) de um UIWebView para um UIImage.
Depois de renderizar o UIImage eu escrevo no disco como PNG para ver o resultado.
Claro que você poderia fazer com o UIImage o que quiser.
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: certifique-se de que o UIWebView esteja totalmente carregado (UIWebViewDelegate ou propriedade de carregamento).