Search code examples
objective-ciosios4uiwebview

How to jump pdf page in UIWebView?


I'm trying to scroll the pdf file by page

here is my code

-(void)viewDidLoad{

NSString *path = [[NSBundle mainBundle] pathForResource:@"myPdffile" ofType:@"pdf"];

NSURL *url = [NSURL fileURLWithPath:path];

NSURLRequest *urlrequest = [NSURLRequest requestWithURL:url];

[webview loadRequest:urlrequest];

webview.scalesPageToFit = YES;

[super viewDidLoad];

}

//goto next page

-(IBAction)nextpage{

        [webview stringByEvaluatingJavaScriptFromString: ?????? ];
}

//goto previous page

-(IBAction)prevpage {

       ?????
}

what should i put after stringByEvaluatingJavaScriptFromString?

do i put same code in "prevpage"?

thanks!


Solution

  • In iOS 5 you can use this statement for page jumping

    [[webView scrollView] setContentOffset:CGPointMake(0,y) animated:YES];
    

    and in below iOS 5 you can use this statement

    [webView stringByEvaluatingJavaScriptFromString:[NSString stringWithFormat:@"window.scrollTo(0.0, %f)", y]];
    

    Where y is the height where you're going to jump.

    Here i am writing some sample code for next and previous page

    -(IBAction) nextPage: (id) sender
    {
        if (currentPage < numberOfPages) 
        {
            float y =  pageHeight * currentPage++;
    
            if (isIOSAbove4) 
            {
                [[webView scrollView] setContentOffset:CGPointMake(0,y) animated:YES];
            }
            else
            {
                [webView stringByEvaluatingJavaScriptFromString:[NSString stringWithFormat:@"window.scrollTo(0.0, %f)", y]];
            }
        }
    }
    

    For previous page:

    -(IBAction) prevPage: (id) sender
    {   
        if (currentPage - 1)
        {
            float y = --currentPage * pageHeight - pageHeight;
            if (isIOSAbove4) 
            {
                [[webView scrollView] setContentOffset:CGPointMake(0,y) animated:YES];
            }
            else
            {
                [webView stringByEvaluatingJavaScriptFromString:[NSString stringWithFormat:@"window.scrollTo(0.0, %f)", y]];
            }
        }
    }
    

    in above sample code isIOSAbove4 is defined in pch file

    #define isIOSAbove4 ([[[UIDevice currentDevice] systemVersion] floatValue] >= 5.0)
    

    Hope above code will solve your problem