在iOS WebView中获取PDF文档高度

问题描述 投票:9回答:6

我试图通过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有一个固定的高度

ios objective-c iphone pdf uiwebview
6个回答
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);

2
投票

试试这个

有这种方法:

size_t CGPDFDocumentGetNumberOfPages(CGPDFDocumentRef document)

这给你number of pages

对于前者

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

下面的代码在height文件中给出了single pagepdf

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

希望能帮助到你。


2
投票

在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)。

最良好的问候


1
投票

这个很容易。

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

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

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

0
投票

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

PDFPage.h

#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

PDFPage.m

#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;
}

如何使用:-

    NSData *pdfData = [NSData dataWithContentsOfURL:[NSURL URLWithString:pdfPath]]; // here pdfPath is webURL

    NSArray * paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString * savePDFAt = ([paths count] > 0) ? [paths objectAtIndex:0] : nil;
    savePDFAt = [NSString stringWithFormat:@"%@/PDFs/",savePDFAt];
    [[NSFileManager defaultManager] createDirectoryAtPath:savePDFAt withIntermediateDirectories:NO attributes:nil error:nil];
    [savePDFAt stringByAppendingPathComponent:"test.pdf"];

    if([pdfData writeToFile:savePDFAt options:0 error:&error])
        NSLog(@"PDF download complete");

    PDFPage *pdfPage = [PDFPage new];
    pdfPage.alpha = 0.0f;
    pdfPage.delegate = self;
    pdfPage.frame = [pdfPage setPdf:pdfPath];

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

© www.soinside.com 2019 - 2024. All rights reserved.