Advertise here




Advertise here

Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

PDF Viewer Tutorial

danielb21danielb21 Posts: 48Tutorial Authors, Registered Users
edited February 2012 in iPhone SDK Tutorials
I have received several requests asking how to view a PDF after creating it natively in the iPhone. Below is a guide to doing just that. It uses the method I am currently using - a UIWebView. This provides you scrolling, zooming and navigating multiple pages without having to write any extra code. So, on to the code!
  1. In your project navigate to or create the directory you want to have the PDF Viewer.
  2. Create a new UIView subclass named 'PDFViewController'.
  3. Also create a new view in your resources directory named 'PDFView'.

This is what your PDFViewController.h should look like:
@interface PDFViewController : UIViewController <UIWebViewDelegate> {
	UIWebView	*webView;
	NSURL	*pdfUrl;
}

@property (nonatomic, retain) IBOutlet UIWebView	*webView;
@property (nonatomic, retain) NSURL			*pdfUrl;

@end

Here we have created UIWebView object named webView, (which has an outlet to Interface Builder) and an NSURL object named pdfUrl.

This is what your PDFViewController.m should look like:
#import "PDFViewController.h"

@implementation PDFViewController

@synthesize webView, pdfUrl;

#pragma mark -
#pragma mark UIViewController methods

// View Did Load method -- Load the PDF
- (void)viewDidLoad {
	[super viewDidLoad];
	// Tells the webView to load pdfUrl
	[webView loadRequest:[NSURLRequest requestWithURL:pdfUrl]];
}
// Dealloc method -- webView, pdfURL
- (void)dealloc {
        [webView release];
        [pdfUrl release];
        [super dealloc];
}

@end

We synthesize our properties, release them in our deallocate method, and in our ViewDidLoad method, tell the webView to load pdfUrl.

Next open PDFView in Interface Builder.
  1. Make File's Owner Class Identity 'PDFViewController'.
  2. Add a Web View on top of the View.
  3. Hook up the view outlet on File's Owner to the View, and the webView outlet on File's Owner to the WebView.
  4. Hook up the delegate outlet on Web View to File's Owner.
  5. Save the file and quit Interface Builder.

Now the only other thing we need to do is Create an instance of PDFViewController, set the pdfUrl property and push the view. I am assuming here that you have some basic knowledge and am not going to get too detailed as to where you put the code that follows. Make sure that in the controller you place this code you have imported 'PDFViewController.h', otherwise it won't work.
// Create an instance of PDFViewController
PDFViewController *controller = [[PDFViewController alloc] initWithNibName:@"PDFView" bundle:nil];
// Get the path to our documents directory
NSArray *documentPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
// This should be our documents directory
NSString *saveDirectory = [documentPath objectAtIndex:0];
// Our PDF is named 'Example.pdf'
NSString *saveFileName = @"Example.pdf";
// Create the full path using our saveDirectory and saveFileName
NSString *finalPath = [saveDirectory stringByAppendingPathComponent:saveFileName];
// Set the pdfUrl to our finalPath
controller.pdfUrl = [NSURL fileURLWithPath:finalPath];
// Push 'controller'
[self.navigationController pushViewController:controller animated:YES];
// Release 'controller'
[controller release];

So, above we created an instance of PDFViewController, created a string that contains the path to our documents directory and a file named 'Example.pdf' in that directory. We set that string to pdfUrl for our controller, and pushed our controller.

That about does it, viewing PDFs on the phone couldn't be much easier than that! Please let me know if you have any questions or if something presented in this tutorial doesn't click.

Thanks!
Post edited by danielb21 on
«1345

Replies

  • sukumar_77sukumar_77 Posts: 203Registered Users
    edited April 2009
    Thanks Daniel for your great work.

    The same approach may be useful to read Microsoft Office Documents i.e. Word, Excel and PPT, if required.
    - Sushil
  • pierresinnepierresinne Posts: 1New Users
    edited May 2009
    danielb21 wrote: »
    I have received several requests asking how to view a PDF after creating it natively in the iPhone. Below is a guide to doing just that. It uses the method I am currently using - a UIWebView. This provides you scrolling, zooming and navigating multiple pages without having to write any extra code. So, on to the code!
    1. In your project navigate to or create the directory you want to have the PDF Viewer.
    2. Create a new UIView subclass named 'PDFViewController'.
    3. Also create a new view in your resources directory named 'PDFView'.

    This is what your PDFViewController.h should look like:
    @interface PDFViewController : UIViewController <UIWebViewDelegate> {
    	UIWebView	*webView;
    	NSURL	*pdfUrl;
    }
    
    @property (nonatomic, retain) IBOutlet UIWebView	*webView;
    @property (nonatomic, retain) NSURL			*pdfUrl;
    
    @end
    

    Here we have created UIWebView object named webView, (which has an outlet to Interface Builder) and an NSURL object named pdfUrl.

    This is what your PDFViewController.m should look like:
    #import "PDFViewController.h"
    
    @implementation PDFViewController
    
    @synthesize webView, pdfUrl;
    
    #pragma mark -
    #pragma mark UIViewController methods
    
    // View Did Load method -- Load the PDF
    - (void)viewDidLoad {
    	[super viewDidLoad];
    	// Tells the webView to load pdfUrl
    	[webView loadRequest:[NSURLRequest requestWithURL:pdfUrl]];
    }
    // Dealloc method -- webView, pdfURL
    - (void)dealloc {
            [webView release];
            [pdfUrl release];
            [super dealloc];
    }
    
    @end
    

    We synthesize our properties, release them in our deallocate method, and in our ViewDidLoad method, tell the webView to load pdfUrl.

    Next open PDFView in Interface Builder.
    1. Make File's Owner Class Identity 'PDFViewController'.
    2. Add a Web View on top of the View.
    3. Hook up the view outlet on File's Owner to the View, and the webView outlet on File's Owner to the WebView.
    4. Hook up the delegate outlet on Web View to File's Owner.
    5. Save the file and quit Interface Builder.

    Now the only other thing we need to do is Create an instance of PDFViewController, set the pdfUrl property and push the view. I am assuming here that you have some basic knowledge and am not going to get too detailed as to where you put the code that follows. Make sure that in the controller you place this code you have imported 'PDFViewController.h', otherwise it won't work.
    // Create an instance of PDFViewController
    PDFViewController *controller = [[PDFViewController alloc] initWithNibName:@"PDFView" bundle:nil];
    // Get the path to our documents directory
    NSArray *documentPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    // This should be our documents directory
    NSString *saveDirectory = [documentPath objectAtIndex:0];
    // Our PDF is named 'Example.pdf'
    NSString *saveFileName = @"Example.pdf";
    // Create the full path using our saveDirectory and saveFileName
    NSString *finalPath = [saveDirectory stringByAppendingPathComponent:saveFileName];
    // Set the pdfUrl to our finalPath
    controller.pdfUrl = [NSURL fileURLWithPath:finalPath];
    // Push 'controller'
    [self.navigationController pushViewController:controller animated:YES];
    // Release 'controller'
    [controller release];
    

    So, above we created an instance of PDFViewController, created a string that contains the path to our documents directory and a file named 'Example.pdf' in that directory. We set that string to pdfUrl for our controller, and pushed our controller.

    That about does it, viewing PDFs on the phone couldn't be much easier than that! Please let me know if you have any questions or if something presented in this tutorial doesn't click.

    Thanks!
    thanks daniel, I'm new to development in iPhone apps, can you assist me with what mean from step 5 downwards, you lost me there. thanks Pierre
  • nevermindnevermind Posts: 14Registered Users
    edited May 2009
    Hi

    first of all, thank you so much for such an easy-to-understand tutorial!
    It's great!
    Could you show me how to show a PDF File that I want to deliver with my app? I mean especially what file path I'd have to type, to point a PDF File that must be found by my PDFView later on the Phone...

    thank you (and sorry for my bad English)

    nevermind
  • sukumar_77sukumar_77 Posts: 203Registered Users
    edited May 2009
    If you are adding a pdf file as a resource file, then following code can be used.

    NSString *pdfPath = [[NSBundle mainBundle] pathForResource:@"pdfFileName" ofType:@".pdf"];
    
    NSURL *pdfURL = [NSURL URLWithString:pdfPath];
    
    - Sushil
  • shermankimbshermankimb Posts: 2New Users
    edited August 2009
    sukumar_77 wrote: »
    If you are adding a pdf file as a resource file, then following code can be used.

    NSString *pdfPath = [[NSBundle mainBundle] pathForResource:@"pdfFileName" ofType:@".pdf"];
    
    NSURL *pdfURL = [NSURL URLWithString:pdfPath];
    


    I'm just getting started at this and what I'm trying to do is to make a simple app where I can click on the icon and a pdf comes up that can be expanded etc. I have created a simple app and then used this tutorial and it's not getting any errors but my pdf isn't showing up. My pdf is a resource file. I have put the code above in a view controller in the loadView section. I have no idea if this is correct - I've tried several other things as well. Can someone tell me where the code above is supposed to go.

    Thanks!
  • sukumar_77sukumar_77 Posts: 203Registered Users
    edited August 2009
    I'm just getting started at this and what I'm trying to do is to make a simple app where I can click on the icon and a pdf comes up that can be expanded etc. I have created a simple app and then used this tutorial and it's not getting any errors but my pdf isn't showing up. My pdf is a resource file. I have put the code above in a view controller in the loadView section. I have no idea if this is correct - I've tried several other things as well. Can someone tell me where the code above is supposed to go.

    Thanks!

    Are you testing onj simulator? If YES, then please test it on device as you will not get any output on simulator.
    - Sushil
  • DGoulianDGoulian Posts: 4New Users Noob
    edited August 2009
    danielb21 - This is a great article - exactly what I have been looking for. Unfortunately, I can't get the code to work after several attempts. Can you post the project for download or email it to me at dgiii@cox.net. Thanks!
    danielb21 wrote: »
    I have received several requests asking how to view a PDF after creating it natively in the iPhone. Below is a guide to doing just that. It uses the method I am currently using - a UIWebView. This provides you scrolling, zooming and navigating multiple pages without having to write any extra code. So, on to the code!
    1. In your project navigate to or create the directory you want to have the PDF Viewer.
    2. Create a new UIView subclass named 'PDFViewController'.
    3. Also create a new view in your resources directory named 'PDFView'.

    This is what your PDFViewController.h should look like:
    @interface PDFViewController : UIViewController <UIWebViewDelegate> {
    	UIWebView	*webView;
    	NSURL	*pdfUrl;
    }
    
    @property (nonatomic, retain) IBOutlet UIWebView	*webView;
    @property (nonatomic, retain) NSURL			*pdfUrl;
    
    @end
    

    Here we have created UIWebView object named webView, (which has an outlet to Interface Builder) and an NSURL object named pdfUrl.

    This is what your PDFViewController.m should look like:
    #import "PDFViewController.h"
    
    @implementation PDFViewController
    
    @synthesize webView, pdfUrl;
    
    #pragma mark -
    #pragma mark UIViewController methods
    
    // View Did Load method -- Load the PDF
    - (void)viewDidLoad {
    	[super viewDidLoad];
    	// Tells the webView to load pdfUrl
    	[webView loadRequest:[NSURLRequest requestWithURL:pdfUrl]];
    }
    // Dealloc method -- webView, pdfURL
    - (void)dealloc {
            [webView release];
            [pdfUrl release];
            [super dealloc];
    }
    
    @end
    

    We synthesize our properties, release them in our deallocate method, and in our ViewDidLoad method, tell the webView to load pdfUrl.

    Next open PDFView in Interface Builder.
    1. Make File's Owner Class Identity 'PDFViewController'.
    2. Add a Web View on top of the View.
    3. Hook up the view outlet on File's Owner to the View, and the webView outlet on File's Owner to the WebView.
    4. Hook up the delegate outlet on Web View to File's Owner.
    5. Save the file and quit Interface Builder.

    Now the only other thing we need to do is Create an instance of PDFViewController, set the pdfUrl property and push the view. I am assuming here that you have some basic knowledge and am not going to get too detailed as to where you put the code that follows. Make sure that in the controller you place this code you have imported 'PDFViewController.h', otherwise it won't work.
    // Create an instance of PDFViewController
    PDFViewController *controller = [[PDFViewController alloc] initWithNibName:@"PDFView" bundle:nil];
    // Get the path to our documents directory
    NSArray *documentPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    // This should be our documents directory
    NSString *saveDirectory = [documentPath objectAtIndex:0];
    // Our PDF is named 'Example.pdf'
    NSString *saveFileName = @"Example.pdf";
    // Create the full path using our saveDirectory and saveFileName
    NSString *finalPath = [saveDirectory stringByAppendingPathComponent:saveFileName];
    // Set the pdfUrl to our finalPath
    controller.pdfUrl = [NSURL fileURLWithPath:finalPath];
    // Push 'controller'
    [self.navigationController pushViewController:controller animated:YES];
    // Release 'controller'
    [controller release];
    

    So, above we created an instance of PDFViewController, created a string that contains the path to our documents directory and a file named 'Example.pdf' in that directory. We set that string to pdfUrl for our controller, and pushed our controller.

    That about does it, viewing PDFs on the phone couldn't be much easier than that! Please let me know if you have any questions or if something presented in this tutorial doesn't click.

    Thanks!
  • GeorgeMGMGeorgeMGM Posts: 1New Users
    edited August 2009
    Hi Guys,
    Im really new to this and i've tried doing this but it just isnt working for me...
    Umm, can someone make a youtube video or something or message me because this really isn't working for me...
    Thanks Guys
    George.
  • DGoulianDGoulian Posts: 4New Users Noob
    edited August 2009
    I have had trouble getting this to work, and I am an experienced programmer. has the author actualy tried this code? Maybe the author would be kind enough to post the working project? Or email to me at dgiii@cox.net.
    Thanks!:)
  • danielb21danielb21 Posts: 48Tutorial Authors, Registered Users
    edited August 2009
    Hey everyone,

    I've been extremely busy and haven't been able to reply till just now. I'm creating a simple project for this right now and will send to all that have PM'ed me.

    Thanks!
    Dan
  • BrianuBrianu Posts: 5New Users
    edited September 2009
    danielb21 wrote: »
    Hey everyone,

    I've been extremely busy and haven't been able to reply till just now. I'm creating a simple project for this right now and will send to all that have PM'ed me.

    Thanks!
    Dan


    Hello!

    Thanks very much for what you've done here!
    I'd also love to get that project, if you would be willing to share.

    I'm at brian@slopart.com

    It is much appreciated!!
  • alexandergrealexandergre Posts: 31Registered Users
    edited September 2009
    Where shall I paste this code? in the AppDelegate?
    anybody? please I tried several times with no success... thanx in advance
    danielb21 wrote: »
    // Create an instance of PDFViewController
    PDFViewController *controller = [[PDFViewController alloc] initWithNibName:@"PDFView" bundle:nil];
    // Get the path to our documents directory
    NSArray *documentPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    // This should be our documents directory
    NSString *saveDirectory = [documentPath objectAtIndex:0];
    // Our PDF is named 'Example.pdf'
    NSString *saveFileName = @"Example.pdf";
    // Create the full path using our saveDirectory and saveFileName
    NSString *finalPath = [saveDirectory stringByAppendingPathComponent:saveFileName];
    // Set the pdfUrl to our finalPath
    controller.pdfUrl = [NSURL fileURLWithPath:finalPath];
    // Push 'controller'
    [self.navigationController pushViewController:controller animated:YES];
    // Release 'controller'
    [controller release];
    
  • rmonsonrmonson Posts: 10Registered Users
    edited September 2009
    sukumar_77 wrote: »
    If you are adding a pdf file as a resource file, then following code can be used.

    NSString *pdfPath = [[NSBundle mainBundle] pathForResource:@"pdfFileName" ofType:@".pdf"];
    
    NSURL *pdfURL = [NSURL URLWithString:pdfPath];
    

    This works well but you have to remove the dot (".") from the file type or it doesn't work. so the "ofType" parameter should be as follows:

    ofType:@"pdf"

    Notice the dot is missing.
  • CoasterCoaster Posts: 57Registered Users
    edited September 2009
    I am afraid i am another that is having trouble with this, i got the PDF create tutorial working, just this one i am doing something wrong.

    Could i also please get you to send me the example project please

    sander15@bigpond.net.au

    Thank you
  • Martin_KuhnMartin_Kuhn Posts: 4New Users
    edited September 2009
    sukumar_77 wrote: »
    If you are adding a pdf file as a resource file, then following code can be used.

    NSString *pdfPath = [[NSBundle mainBundle] pathForResource:@"pdfFileName" ofType:@".pdf"];
    
    NSURL *pdfURL = [NSURL URLWithString:pdfPath];
    

    Hallo.

    Thanks for this very good tutorial!
    Please show me the exact position of this code.
    I can't make it work correct.

    Thanks Martin
  • shermankimbshermankimb Posts: 2New Users
    edited October 2009
    I'm now getting back to working on this and also still having trouble. I would love to see the example project!

    I'm one of those who is trying to load the pdf from the Resources folder.

    kksherman@austin.rr.com

    Thanks
  • wolverinewolverine Posts: 181Registered Users
    edited October 2009
    danielb21 wrote: »
    Hey everyone,

    I've been extremely busy and haven't been able to reply till just now. I'm creating a simple project for this right now and will send to all that have PM'ed me.

    Thanks!
    Dan

    Please send the project to me too. :)
  • wolverinewolverine Posts: 181Registered Users
    edited October 2009
    I checked this thing and its working perfectly in the simulator as well as device. I just added a PDF as a resource and checked it. And its fine.
  • momolgtmmomolgtm Posts: 13Registered Users *
    edited October 2009
    danielb21 wrote: »
    Hey everyone,

    I've been extremely busy and haven't been able to reply till just now. I'm creating a simple project for this right now and will send to all that have PM'ed me.

    Thanks!
    Dan



    Could i also please get you to send me the example project please

    momolgtm@gmail.com

    Thank you
  • hobnobhobnob Posts: 2New Users
    edited October 2009
    danielb21 wrote: »
    Hey everyone,

    I've been extremely busy and haven't been able to reply till just now. I'm creating a simple project for this right now and will send to all that have PM'ed me.

    Thanks!
    Dan


    Hello, could you email it to me please as well, thanks. I've messaged you.
  • magickmagick Posts: 3New Users
    edited July 2012
  • shiva.0537shiva.0537 Posts: 54Registered Users
    edited October 2009
    Hi,

    I am also looking for same kind of application. Could you please send me code, if you are willing to share. My mail id is sambasivarao@web1infotech.com

    Thanks
    shiva
  • SumitSumit Posts: 5New Users
    edited November 2009
    Hi,

    Thanks for the tutorial. It was really a detailed on.
    It would be great if you can send me the sample code too.
    My email id : s_utreja@yahoo.com

    Thanks,
  • aderringtonaderrington Posts: 46Registered Users
    edited December 2009
    Hi, Any chance someone could forward the example project file on to me aswell??
    Many thanks! (Andrew @ Aderrington.co.uk)
    Andrew
  • tjoozeytjoozey Posts: 1New Users
    edited December 2009
    Simulator does not display PDF file. Placed instance code in main.m file.
«1345
Sign In or Register to comment.