在iOS WebView中获取PDF文档高度

时间:2015-08-21 11:42:49

标签: ios objective-c iphone pdf uiwebview

我尝试通过UIWebViewNSURL中显示PDF。它工作正常。

我不知道pdf文件的高度。所以有时它会创建空白区域或需要滚动。 PDF也可能包含多个页面。

如果它包含多个页面,我只想显示第一页。

我的代码如下:

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];

目前,WebView有一个固定的高度

6 个答案:

答案 0 :(得分:3)

Pradumna Patil的回答是正确的。我把你的代码和他的代码结合起来,并且运行正常。只需将以下行粘贴到您的项目中,然后自己查看:

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);

答案 1 :(得分:2)

试试这个

有这种方法:

size_t CGPDFDocumentGetNumberOfPages(CGPDFDocumentRef document)

这会为您提供number of pages

对于前。

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

下面的代码在height文件中提供了single page的{​​{1}}

pdf

希望它有所帮助。

答案 2 :(得分:1)

这个很容易。

您必须访问webView的滚动视图而不是webview本身:

CGFloat totalHeight = self.webView.scrollView.contentSize.height;

答案 3 :(得分:1)

在Swift中你可以做到:

let documents = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first
let writePath = documents?.appending("/myPdf.pdf")
let pdf: CGPDFDocument! = CGPDFDocument(URL.init(fileURLWithPath: writePath!) as CFURL)`enter code here`
let firstPage: CGPDFPage = pdf.page(at: 1)!
let heightFirstPage :CGRect =  firstPage.getBoxRect(.mediaBox) 
var heightPagePdf : CGFloat = heightFirstPage.height;

变量'pdf'也有一个属性'numberOfPages',因此你可以知道pdf文档的整个高度(pdf.numberOfPages * heightPagePdf)。

最好的考虑

答案 4 :(得分:0)

试试这个......工作正常

 NSURL* pdfFileUrl = targetURL;
CGPDFDocumentRef pdf = CGPDFDocumentCreateWithURL((CFURLRef)pdfFileUrl);

CGFloat pdfHeight = 0;
NSUInteger totalNum = CGPDFDocumentGetNumberOfPages(pdf);
 for(int i = 0; i < totalNum; i++ ) {
    CGPDFPageRef myPageRef=CGPDFDocumentGetPage(pdf, i+1);
    CGRect cropBox = CGPDFPageGetBoxRect(myPageRef, kCGPDFCropBox);
    pdfHeight+=cropBox.size.height;
    int pageRotation = CGPDFPageGetRotationAngle(myPageRef);
    CGSize pageVisibleSize = CGSizeMake(cropBox.size.width, cropBox.size.height);
    if ((pageRotation == 90) || (pageRotation == 270) ||(pageRotation == -90)) {
        pageVisibleSize = CGSizeMake(cropBox.size.height, cropBox.size.width);
    }
}
NSLog(@"%f",pdfHeight);

答案 5 :(得分:0)

我没有在webView中加载pdf,而是建议你在UIView中绘制PDF,就像我在自己的项目中完成的那样,它的工作非常完美。 下面是我的UIView子类,它在UIView上下文中绘制pdf。

PDFPage.h

Class[] classes = Constants.class.getDeclaredClasses();     
    for(Class innerClass: classes){
        //System.out.println(innerClass.getName());
        Field[] fields = innerClass.getDeclaredFields();
        for(Field field : fields){
            //System.out.println(field.getName());
            //your implementation
        }           
    }

PDFPage.m

#import <UIKit/UIKit.h>

@protocol PDFPageDelegate;



@interface PDFPage : UIView

@property    uint                   currentPage;
@property    unsigned long          totalPages;
@property    CGRect                 pageRect;
@property    NSString               *pdfPath;
@property    id<PDFPageDelegate>    delegate;


- (CGRect)setPdf:(NSString*)filePath;
- (void)swipeLeft;
- (void)swipeRight;
- (void)setPageNumber:(NSUInteger )targetPageNumber;

@end







@protocol PDFPageDelegate <NSObject>

- (void)pdfWillSwipeToLeft:(uint)upcommingPageNumber;
- (void)pdfWillSwipeToRight:(uint)upcommingPageNumber;
- (void)pdfTaped:(CGPoint)tapAt;
- (void)pdfDoubleTapped;

@end

使用方法: -

#import "PDFPage.h"

@implementation PDFPage

@synthesize pageRect        = _pageRect;
@synthesize currentPage     = _currentPage;
@synthesize totalPages      = _totalPages;
@synthesize delegate        = _delegate;
@synthesize pdfPath         = _pdfPath;




- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {}

    _currentPage = 1;

    UISwipeGestureRecognizer *swipeLeft = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(swipeLeft)];
    swipeLeft.direction = UISwipeGestureRecognizerDirectionLeft;
    [self addGestureRecognizer:swipeLeft];


    UISwipeGestureRecognizer *swipeRight = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(swipeRight)];
    swipeRight.direction = UISwipeGestureRecognizerDirectionRight;
    [self addGestureRecognizer:swipeRight];

    return self;
}



- (void)setPageNumber:(NSUInteger )targetPageNumber
{
    _currentPage = (uint)targetPageNumber;

    [self setNeedsDisplay];
    [UIView transitionWithView:self duration:0.5
                   options:UIViewAnimationOptionTransitionCrossDissolve
                animations:^{
                    [self.layer displayIfNeeded];
                } completion:nil];
}

- (void)swipeLeft
{
    if(_currentPage == _totalPages)
        return;

    _currentPage++;

    [_delegate pdfWillSwipeToLeft:_currentPage];

    [self setNeedsDisplay];
    [UIView transitionWithView:self duration:0.5
                   options:UIViewAnimationOptionTransitionCrossDissolve
                animations:^{
                    [self.layer displayIfNeeded];
                } completion:nil];
}

- (void)swipeRight
{
    if(_currentPage == 1)
        return;


    _currentPage--;


    [_delegate pdfWillSwipeToRight:_currentPage];


    [self setNeedsDisplay];
    [UIView transitionWithView:self duration:0.5
                   options:UIViewAnimationOptionTransitionCrossDissolve
                animations:^{
                    [self.layer displayIfNeeded];
                } completion:nil];

}



- (void)drawRect:(CGRect)rect
{
    CGContextRef ctx = UIGraphicsGetCurrentContext();

    // PDF might be transparent, assume white paper
    [[UIColor whiteColor] set];
    CGContextFillRect(ctx, rect);

    // Flip coordinates
    CGContextGetCTM(ctx);
    CGContextScaleCTM(ctx, 1, -1);
    CGContextTranslateCTM(ctx, 0, -rect.size.height);

    // url is a file URL
    CFURLRef pdfURL = (__bridge CFURLRef)[NSURL fileURLWithPath:_pdfPath];
    CGPDFDocumentRef pdf = CGPDFDocumentCreateWithURL(pdfURL);
    CGPDFPageRef page1 = CGPDFDocumentGetPage(pdf, _currentPage);

    // get the rectangle of the cropped inside
    CGRect mediaRect = CGPDFPageGetBoxRect(page1, kCGPDFCropBox);

    CGContextScaleCTM(ctx, rect.size.width / mediaRect.size.width,
                  rect.size.height / mediaRect.size.height);
    CGContextTranslateCTM(ctx, -mediaRect.origin.x, -mediaRect.origin.y);

    // draw it
    CGContextDrawPDFPage(ctx, page1);
    CGPDFDocumentRelease(pdf);
}



- (CGRect)setPdf:(NSString*)filePath
{

    _pdfPath =filePath;
    _currentPage = 1;
    CFURLRef pdfURL = (__bridge CFURLRef)[NSURL fileURLWithPath:_pdfPath];

    CGPDFDocumentRef pdf = CGPDFDocumentCreateWithURL(pdfURL);
    CGPDFPageRef page = CGPDFDocumentGetPage(pdf,_currentPage);

    _pageRect = CGPDFPageGetBoxRect(page, kCGPDFCropBox);
    _totalPages = (CGPDFDocumentGetNumberOfPages(pdf));
    [self setNeedsDisplay];
    [UIView transitionWithView:self duration:0.5
                   options:UIViewAnimationOptionTransitionCrossDissolve
                animations:^{
                    [self setNeedsDisplay];
                } completion:nil];

    CGRect finalRect = CGRectMake(0, 0, _pageRect.size.width, _pageRect.size.height);

    return finalRect;
}

然后将此pdfPage添加到自己的视图或滚动条。