2015-08-21 13 views
9

UIWebView aracılığıyla NSURL aracılığıyla PDF görüntülemeye çalışıyorum. İyi çalışıyor.iOS belgesindeki PDF belge yüksekliğini al

Ama Pdf belgenin yüksekliğini bilmiyorum. Yani bazen boş alan yaratır veya kaydırmaya ihtiyaç duyar. PDF ayrıca birden çok sayfa içerebilir.

Sadece çok sayfalı sayfalar varsa ilk sayfayı göstermek istiyorum.

Kodum şu şekilde olmaktadır: WebView sabit yüksekliği

+0

İhtiyacınız olan tek şey belgenin yüksekliğiyse, bu soru bir kopyadır. Belirli bir sayfada yer alan alan miktarına ihtiyacınız varsa, yaklaşımınızı yeniden gözden geçirmek isteyebilirsiniz çünkü bir PDF, Doğaya Dayalı Belge Biçimi, platformları ve tarayıcıları aşmaktadır. Bu beyaz alan, belgenin yaratıcısı tarafından tasarlandıysa, büyük olasılıkla PDF belgelerinin sayfalar olarak oluşturulduğu zaman, bunu görüntülemeyi düşünebilirsiniz. – SwiftArchitect

cevap

2

sahiptir Şu anda

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

deneyin bu yöntem yoktur

:

size_t CGPDFDocumentGetNumberOfPages(CGPDFDocumentRef document) 

verir numberofpages.

Örn. Kodun altında

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

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

Umarım yardımcı olur pdf dosyada singlepage arasında height verir.

+0

Cevabınız için teşekkürler! ama yanlış yükseklik veriyor! , ör. 800 yükseklik verir, ancak web görünümü için 800 px yükseklik ayarlarsam boş alan çok görünüyor! – user2526811

+0

@ user2526811 CGPDFPageGetBoxRect'in boyutları, belgenin yerel boyutlarıdır, web görünümünün yüksekliğini "web_large.frame.size.width * (height/width)" olarak ayarlamanız gerekir, bu nedenle yükseklik, belge boyutunun bir oranıdır – SomeGuy

0

deneyin bu .. Onun çalışma Onun yerine ben kendi projesinde yapmış ve mükemmel çalışıyor gibi mi, UIView içinde PDF çizmek önermek istiyorum Web görünümü yükleme pdf ince

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

Cevabınız için teşekkürler! Bekle .. – user2526811

+0

'u kontrol ediyorum üzgünüm! ama bu çalışmıyor! Eğer pdf'nin sadece 1 sayfası olduğunu düşünürsem aynı cevaptır. 800 olarak yükseklik verir ancak çok fazla boş alan gösterir! – user2526811

0

. Aşağıda, UIView bağlamında pdf çizen UIView alt sınıfı var.

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

nasıl kullanılır: -

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

Sonra kendiliğin görünümüne bu pdfPage eklemek veya Kaydıraç için.

+0

Örnekte '' pdfPath '' değişkeni bildirimi yok –

1

Bu kolay.

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

^neden bu cevap olarak kabul edilmiyor, bu, web sayfasının içindeki pdf içeriğinin istenen yüksekliğini oldukça düzgün bir şekilde veriyor –

+0

Kişinin özellikle söylediği " Ama __I pdf document__ yüksekliğini bilmiyorum "ve sorunun başlığı:" iOS WebView'da PDF belge yüksekliğini al "cevabımın bu koşullar için oldukça iyi olduğunu düşünüyorum @SwiftArchitect bunu cevaplayan herkese cevap verdi. Farklı bir yön –

+0

Sağ. Yemin edebilirdim ki böyle başlamadı. Ardından bu, http://stackoverflow.com/questions/20755231/calculate-pdf-content-height-in-ios veya http://stackoverflow.com/questions/3045587/how-to-get-actual adresinin kopyası değildir. -PDF sayfalık boy-in-ipad? – SwiftArchitect

3

Pradumna Patil cevabı doğrudur:

Sen webview kendisi Web görünümü scrollview erişmek zorunda. Kodunu onunla birleştirdim ve işe yaradı.Sadece projenize aşağıdaki satırları yapıştırın ve kendiniz görün:

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

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

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

benim için çalışmıyor. CGPDFDocumentCreateWithURL eş zamansız mı? – user1709076

0

Swift de yapabileceğiniz:

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; 

değişken 'pdf' Bildiğiniz böylece de, bir mülkiyet 'NUMBEROFPAGES' vardır pdf belgesinin tüm yüksekliği (pdf.numberOfPages * heightPagePdf).

saygılarımla

İlgili konular