如何加载UIWebview中心的PDF文件

我在ios开发中是新的。我试图在UIWebview中心显示一个pdf。我有一个PDF在mainbundle.Here是我的PDF看起来像现在加载在一个UIWebView:(我把棕色渐变为UIWebView的背景,所以你可以看到我的意思更好)。 在这里输入图像说明

- (void)viewDidLoad { UIWebView *theWebView = [[UIWebView alloc] initWithFrame:[self.view bounds]]; [theWebView setContentMode:UIViewContentModeScaleAspectFit]; [theWebView setAutoresizingMask:UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth]; [theWebView setScalesPageToFit:YES]; NSString *filePath = [[NSBundle mainBundle] pathForResource:@"test" ofType:@"pdf"]; NSURL *filePathURL = [NSURL fileURLWithPath:filePath]; [theWebView loadRequest:[NSURLRequest requestWithURL:filePathURL]]; [self.view addSubview:theWebView]; [super viewDidLoad]; } 

我想以此为中心,使底部边距与顶部边距相同。 我如何用PDF(本地)来做到这一点?

 CGRect rect = [[UIScreen mainScreen] bounds]; CGSize screenSize = rect.size; UIWebView *webView = [[UIWebView alloc] initWithFrame:CGRectMake(0,0,screenSize.width,screenSize.height)]; NSString *path = [[NSBundle mainBundle] pathForResource:@"pdf" ofType:@"pdf"]; NSURL *targetURL = [NSURL fileURLWithPath:path]; NSURLRequest *request = [NSURLRequest requestWithURL:targetURL]; [webView loadRequest:request]; [self.view addSubview:webView]; 

不知道这是否是您的问题的理想解决scheme。

首先获取PDF的宽度和高度==>

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

Pageref是PDF页面的参考。

 CGSize pdfSize = CGSizeMake(width, height); //Create one superView to webview UIView *supView = [[UIView alloc] initWithFrame:[self.view bounds]]; supView.backgroundColor=[UIColor colorWithRed:0.663 green:0.855 blue:0.341 alpha:1] 

//然后webview

 UIWebView *theWebView = [[UIWebView alloc] initWithFrame:CGRectMake(0,0, pdfSize.width, pdfSize.height)]]; [theWebView setContentMode:UIViewContentModeScaleAspectFit]; [theWebView setAutoresizingMask:UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth]; [theWebView setScalesPageToFit:YES]; NSString *filePath = [[NSBundle mainBundle] pathForResource:@"test" ofType:@"pdf"]; NSURL *filePathURL = [NSURL fileURLWithPath:filePath]; [theWebView loadRequest:[NSURLRequest requestWithURL:filePathURL]]; [supView addSubview: theWebView]; [self.view addSubview: supView]; 

编辑:

获取Pageref(部分),

 NSString *filePath = [[NSBundle mainBundle] pathForResource:@"test" ofType:@"pdf"]; NSURL *filePathURL = [NSURL fileURLWithPath:filePath]; CFURLRef pdfURL = (__bridge CFURLRef)[[NSURL alloc] initFileURLWithPath:filePath]; //file ref CGPDFDocumentRef pdfDocRef = CGPDFDocumentCreateWithURL((CFURLRef) pdfURL); CGPDFPageRef PageRef = CGPDFDocumentGetPage(pdfDocRef, 1); float width = CGPDFPageGetBoxRect(page1, kCGPDFMediaBox).size.width; float height = CGPDFPageGetBoxRect(page1, kCGPDFMediaBox).size.height; NSLog(@"%f %f",height,width);