Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get PDF document height in iOS WebView

I am try to display a PDF in UIWebView via NSURL. It works fine.

But I do not know the height of pdf document. So sometimes it creates blank space or need to scroll. The PDF may also contain multiple pages.

I only want to show first page if it contain multi pages.

My code is as follow:

NSURL *url = [NSURL URLWithString:@"http://www.eecs.harvard.edu/econcs/pubs/online.pdf"];
 NSURLRequest * request = [NSURLRequest requestWithURL:url];
    [web_large loadRequest:request];
    [web_large setScalesPageToFit:YES];

Right now, the WebView has a fixed height

like image 530
user2526811 Avatar asked Aug 21 '15 11:08

user2526811


2 Answers

Pradumna Patil's answer is correct. I combined your code with his, and it worked fine. Just paste the following lines into your project and see for yourself:

UIWebView *web_large = [[UIWebView alloc]init];
[self.view addSubview:web_large];

NSURL *url = [NSURL URLWithString:@"https://www.truthinadvertising.org/wp-content/uploads/2014/09/App-Store-Review-Guidelines.pdf"];
NSURLRequest * request = [NSURLRequest requestWithURL:url];
[web_large loadRequest:request];
[web_large setScalesPageToFit:YES];

CGPDFDocumentRef pdfDocumentRef = CGPDFDocumentCreateWithURL((CFURLRef)url);
CGPDFPageRef pdfPageRef = CGPDFDocumentGetPage(pdfDocumentRef, 1);

CGRect pdfPageRect = CGPDFPageGetBoxRect(pdfPageRef, kCGPDFMediaBox);

float width = pdfPageRect.size.width;
float height = pdfPageRect.size.height;

CGRect screenRect = [[UIScreen mainScreen]bounds];
web_large.frame = CGRectMake(0, 0, screenRect.size.width, height*screenRect.size.width/width);
like image 88
turingtested Avatar answered Nov 11 '22 21:11

turingtested


Try this

There is this method:

size_t CGPDFDocumentGetNumberOfPages(CGPDFDocumentRef document)

That gives you the number of pages.

For ex.

NSURL *pdfUrl = [NSURL fileURLWithPath:yourPath];    
CGPDFDocumentRef document = CGPDFDocumentCreateWithURL((CFURLRef)pdfUrl);

Below code gives height of single page in pdf file

  float width = CGPDFPageGetBoxRect(pdfPageRef, kCGPDFMediaBox).size.width;
    float height = CGPDFPageGetBoxRect(pdfPageRef, kCGPDFMediaBox).size.height;

Hope it helps.

like image 2
Pradumna Patil Avatar answered Nov 11 '22 21:11

Pradumna Patil