Open document in web view for iOS

I recently came across the scenario were I had to open some pdfs that came with the application. I didn't want to use the "UIDocumentInteractionController" class for this so I stumbled upon some forum posts that showed me how to do it using a webview. It turns out that UIWebView can support a range of media files:

  • Excel (.xls)
  • Keynote (.key.zip)
  • Numbers (.numbers.zip)
  • Pages (.pages.zip)
  • PDF (.pdf)
  • Powerpoint (.ppt)
  • Word (.doc)

Apple documentation can be found here

Below is the code used to open a PDF file

-(void)openPDF{

NSString *pdfPath = [[NSBundle mainBundle] pathForResource:@"DontHardCode" ofType:@"pdf"];
    UIWebView *webView = [[UIWebView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height)]; //PDF should be shown in entire screen
    webView.scalesPageToFit = YES; //PDF page should be scaled to display whole page in screen
    webView.autoresizingMask = (UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight);
    [self.view addSubview:webView];
    NSURL *pdfURL = [NSURL fileURLWithPath:pdfPath];
    [webView loadRequest:[NSURLRequest requestWithURL:pdfURL]];
}