Create a PDF from a Microsoft document loaded in UIWebView

suggest change

UIWebView is deprecated. This sample uses its viewPrintFormatter.

#define kPaperSizeA4 CGSizeMake(595.2, 841.8)

Add a category on UIPrintPageRenderer. This is not a protocol.

@interface UIPrintPageRenderer (PDF)

- (NSData*) printToPDF;

@end

@implementation UIPrintPageRenderer (PDF)

- (NSData*) printToPDF
{
    NSMutableData *pdfData = [NSMutableData data];
    UIGraphicsBeginPDFContextToData( pdfData, self.paperRect, nil );
    [self prepareForDrawingPages: NSMakeRange(0, self.numberOfPages)];
    CGRect bounds = UIGraphicsGetPDFContextBounds();
    for ( int i = 0 ; i < self.numberOfPages ; i++ )
    {
        UIGraphicsBeginPDFPage();
        [self drawPageAtIndex: i inRect: bounds];
    }
    UIGraphicsEndPDFContext();
    return pdfData;
}
@end

Call this after the document has finished loading in the UIWebView. directoryPath is the file path to write. paperRect and printableRect are set with key-value coding because those properties are not public setters.

- (void)createPDF:(UIWebView *)webView {
    UIPrintPageRenderer *render = [[UIPrintPageRenderer alloc] init];
    [render addPrintFormatter:webView.viewPrintFormatter startingAtPageAtIndex:0];

    CGFloat padding = 10.0f;
    CGRect paperRect = CGRectMake(0, 0, kPaperSizeA4.width, kPaperSizeA4.height);
    CGRect printableRect = CGRectMake(padding, padding, kPaperSizeA4.width - (padding * 2), kPaperSizeA4.height - (padding * 2));

    [render setValue:[NSValue valueWithCGRect:paperRect] forKey:@"paperRect"];
    [render setValue:[NSValue valueWithCGRect:printableRect] forKey:@"printableRect"];

    NSData *pdfData = [render printToPDF];
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        if (pdfData) {
            [pdfData writeToFile:directoryPath atomically:YES];
        } else {
            NSLog(@"PDF could not be created");
        }
    });
}

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents