Подтвердить что ты не робот

Получите PDF/PNG как вывод из UIWebView или UIView

Есть ли способ получить содержимое UIWebView и преобразовать его в файл PDF или PNG? Я хотел бы получить аналогичный вывод на тот, который доступен на Mac, выбрав, например, кнопку PDF при печати из Safari. Я предполагаю, что это невозможно/встроено еще, но, надеюсь, я буду удивлен и найду способ получить содержимое из веб-представления в файл.

Спасибо!

4b9b3361

Ответ 1

Вы можете использовать следующую категорию в 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

Создание изображения с веб-представления прост:

UIImage* image = nil;

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

Как только у вас есть изображение, вы можете сохранить его как PNG.

Создание PDF файлов также возможно очень похоже, но только на еще неизданной версии iPhone OS.

Ответ 3

@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

Приведенный ниже код преобразует (полный) контент 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 или свойство загрузки).