Basically, I want to click a button in my web view that will download a PDF from a remote website and display it with a close/back button. I'm using QLViewController so people can pinch-zoom the PDF, and I'm using PhoneGap 3.0 with XCode 5 to code it.
Here's the code for my plugin that will show the new view with the back button but I can't seem to get the PDF to show. Any ideas?
#import "PDFViewer.h"
#import <Cordova/CDV.h>
#implementation PDFViewer
- (void)loadRemotePdf:(CDVInvokedUrlCommand*)command
{
CDVPluginResult* pluginResult = nil;
NSString *website = [command.arguments objectAtIndex:0];
NSString *filename = [command.arguments objectAtIndex:1];
if (website != nil && [website length] > 0) {
CGRect rect = [[UIScreen mainScreen] bounds];
CGSize screenSize = rect.size;
UIWindow *window = [[UIApplication sharedApplication] keyWindow];
UIWebView *webView = [[UIWebView alloc] initWithFrame:CGRectMake(0,0,screenSize.width,screenSize.height)];
webView.autoresizesSubviews = YES;
[webView canGoBack];
webView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
// NSURL *myUrl = [NSURL URLWithString:website];
// NSURLRequest *myRequest = [NSURLRequest requestWithURL:myUrl];
// [webView loadRequest:myRequest];
// [window addSubview: webView];
NSURL *url = [NSURL URLWithString:website];
NSData *urlData = [NSData dataWithContentsOfURL:url];
if ( urlData )
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
filePath = [NSString stringWithFormat:#"%#/%#", documentsDirectory, filename];
[urlData writeToFile:filePath atomically:YES];
// Create test view controller
QLPreviewController *previewer = [[QLPreviewController alloc] init];
previewer.dataSource = self;
previewer.delegate = self;
// Create navigation controller
UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:previewer];
[window addSubview: [nav view]];
[window makeKeyAndVisible];
}
pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK];
}
else {
pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR];
}
// return result
[self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
}
#pragma mark - QLPreviewControllerDataSource
- (NSInteger)numberOfPreviewItemsInPreviewController:(QLPreviewController *)controller {
return 1;
}
- (id <QLPreviewItem>) previewController: (QLPreviewController *) controller previewItemAtIndex: (NSInteger) index;
{
NSURL *fileURL = [NSURL fileURLWithPath: filePath];
return fileURL;
}
#end
Yes, this can be done with the UIWebView.
If you are trying to display a PDF file residing on a server somewhere, you can simple load it to your web view directly:
UIWebView *webView = [[UIWebView alloc] initWithFrame:CGRectMake(10, 10, 200, 200)];
NSURL *targetURL = [NSURL URLWithString:#"http://developer.apple.com/iphone/library/documentation/UIKit/Reference/UIWebView_Class/UIWebView_Class.pdf"];
NSURLRequest *request = [NSURLRequest requestWithURL:targetURL];
[webView loadRequest:request];
[self.view addSubview:webView];
[webView release];
//Or if you have a PDF file bundled with your application (in this example named "document.pdf"):
UIWebView *webView = [[UIWebView alloc] initWithFrame:CGRectMake(10, 10, 200, 200)];
NSString *path = [[NSBundle mainBundle] pathForResource:#"document" ofType:#"pdf"];
NSURL *targetURL = [NSURL fileURLWithPath:path];
NSURLRequest *request = [NSURLRequest requestWithURL:targetURL];
[webView loadRequest:request];
[self.view addSubview:webView];
[webView release];
Related
I want to display MSOffice extensions in webview. Is this possible?
I've tried this:
NSString *resourceDocPath = [[NSString alloc] initWithString:[[[[NSBundle mainBundle] resourcePath] stringByDeletingLastPathComponent] stringByAppendingPathComponent:#"Documents"]];
NSString *filePath = [resourceDocPath
stringByAppendingPathComponent:#"myPDF.pdf"];
[pdfData writeToFile:filePath atomically:YES];
CGRect rect = [[UIScreen mainScreen] bounds];
CGSize screenSize = rect.size;
UIWebView *webView = [[UIWebView alloc] initWithFrame:CGRectMake(0,0,screenSize.width,screenSize.height)];
// Now create Request for the file that was saved in your documents folder
//UIWebView *webView = [[UIWebView alloc] initWithFrame:CGRectMake(10, 250, self.view.frame.size.width, 300)];
NSURL *targetURL = [NSURL URLWithString:fileurl];
NSURLRequest *request = [NSURLRequest requestWithURL:targetURL];
[webView loadRequest:request];
[self.view addSubview:webView];
But I get the message:
"An error occured while reading the document".
Try below if your ppt file is drag dropped in your project
[webView loadRequest:[NSURLRequest requestWithURL:
[NSURL fileURLWithPath:[[NSBundle mainBundle]
pathForResource:#"FileName" ofType:#"ppt"]isDirectory:NO]]];
If you are getting your file from server in form of NSData then use below
NSURL *url=[NSURL URLWithString:[#"yourURL" stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
NSData* responseData = [NSData dataWithContentsOfURL: url];
[webView loadData:responseData MIMEType:#"application/ppt"
textEncodingName:#"utf-8" baseURL:[NSURL URLWithString:#""]];
I have the pdf file in local resource folder i want to open this file using UIWebView and user can read. But the PDF file is not displaying to read.
NSString *pathToBundle = [[NSBundle mainBundle] bundlePath];
NSURL *baseURL = [NSURL fileURLWithPath:pathToBundle];
NSString *htmlFile = [[NSBundle mainBundle] pathForResource:#"Insupen_User_Guide" ofType:#"pdf"];
NSString *htmlString = [NSString stringWithContentsOfFile:htmlFile encoding:NSUTF8StringEncoding error:nil];
//CGRect fullScreenRect=[[UIScreen mainScreen]applicationFrame];
catalogue=[[UIWebView alloc]initWithFrame:CGRectMake(50,400,600,600)];
[catalogue loadHTMLString:htmlString baseURL:baseURL];
catalogue.delegate=self;
[self.view addSubview:catalogue];
try this.
NSString *strPath = [[NSBundle mainBundle]pathForResource:#"Insupen_User_Guide" ofType:#"pdf"];
[catalogue loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:[strPath stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]]]];
maybe this will help you.
NSString *path = [[NSBundle mainBundle]pathForResource:#"HR" ofType:#"pdf"];
NSURL *targeturl = [NSURL fileURLWithPath:path];
NSURLRequest *request = [NSURLRequest requestWithURL:targeturl];
// _webview = [[UIWebView alloc]init];
[[_webview scrollView] setContentOffset:CGPointMake(0, 500) animated:YES];
[_webview stringByEvaluatingJavaScriptFromString:[NSString stringWithFormat:#"window.scrollTo(0.0, 50.0)"]];
[_webview loadRequest:request];
// worked for me perfectly you can try this
In the code you posted you are turning the contents of the PDF file into a UTF8 encoded string and displaying the string inside the web view, this is not what you want.
Instead, you need to make a NSURLRequest pointing to the local PDF and load the request in the web view like so
NSString *pdfPath = [[NSBundle mainBundle] pathForResource:#"Insupen_User_Guide" ofType:#"pdf"];
NSURL *pdfUrl = [NSURL fileURLWithPath:pdfPath];
NSURLRequest *pdfUrlRequest = [NSURLRequest requestWithURL:pdfUrl];
[catalogue loadRequest:pdfUrlRequest];
You can also display PDF in UIDocumentInteractionController using this.
UIDocumentInteractionController *docController = [UIDocumentInteractionController interactionControllerWithURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:#"PDF file name" ofType:#"pdf"]]];
docController.delegate = self;
//[DocView addSubview:docController];
[docController presentPreviewAnimated:YES];
And add these delegate methods in your class.
#pragma mark documentInteractionController methods
- (UIViewController *)documentInteractionControllerViewControllerForPreview:(UIDocumentInteractionController *)controller {
return self;
}
- (UIView *)documentInteractionControllerViewForPreview:(UIDocumentInteractionController *)controller {
return self.view;
}
- (CGRect)documentInteractionControllerRectForPreview:(UIDocumentInteractionController *)controller {
return self.view.frame;
}
- (BOOL)documentInteractionController:(UIDocumentInteractionController *)controller canPerformAction:(SEL)action{
return FALSE;
}
i triad to click on URL which is in PDF file. and PDF file opened in UIWebView, but i cant able to click on URL.
any one tell me how to open URL which is in PDF file.
UIWebView *webView = [[UIWebView alloc] initWithFrame:CGRectMake(0, 20, 320, 460)];
NSURL *targetURL = [NSURL URLWithString:#"http://partners.adobe.com/public/developer/en/acrobat/PDFOpenParameters.pdf"];
NSURLRequest *request = [NSURLRequest requestWithURL:targetURL];
[webView loadRequest:request];
[self.view addSubview:webView];
In you webView deleget method, first of detect the url from PDF and then open in webview or etc. I have used following method to do this, may be its helping you :
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{
NSURL *requestURL = [[ request URL] retain];
if (([[requestURL scheme] isEqualToString: #"http"] || [[requestURL scheme] isEqualToString: #"https"]) && (navigationType == UIWebViewNavigationTypeLinkClicked))
{
// Your method when tap on url found in PDF
}
}
If you have a PDF file in Local storage
NSString *html = [NSString stringWithContentsOfFile:path1 encoding:NSUTF8StringEncoding error:nil];
[self.webView loadHTMLString:html baseURL:[NSURL fileURLWithPath:[[NSBundle mainBundle]bundlePath]]];
If you have Access to file From the Internet
- (void) loadRemotePdf
{
CGRect rect = [[UIScreen mainScreen] bounds];
CGSize screenSize = rect.size;
UIWebView *myWebView = [[UIWebView alloc] initWithFrame:CGRectMake(0,0,screenSize.width,screenSize.height)];
webView.autoresizesSubviews = YES;
webView.autoresizingMask=(UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth);
NSURL *myUrl = [NSURL URLWithString:#"http://www.mysite.com/test.pdf"];
NSURLRequest *myRequest = [NSURLRequest requestWithURL:myUrl];
[webView loadRequest:myRequest];
[window addSubview: myWebView];
[myWebView release];
}
I am using both approaches by reading inner HTML content of a webView and by reading AsciiString but in both approaches when i convert it into PDF formate data truncates. Please look my code and tell me where i am wrong.
-(NSData *)createPDFfromUIWebView:(UIWebView*)webView saveToDocumentsWithFileName:(NSString*)aFilename
{
// Creates a mutable data object for updating with binary data, like a byte array
[self removeFileByName];
// NSString *heightStr = [webView stringByEvaluatingJavaScriptFromString:#"document.body.scrollHeight;"];
// NSString *heightStr = [webView stringByEvaluatingJavaScriptFromString:#"document.body.innerHTML"];
// NSString *heightStr = [webView stringByEvaluatingJavaScriptFromString:#"document.documentElement.outerHTML"];
// NSString *heightStr = (NSString *)[webView stringByEvaluatingJavaScriptFromString:#"getParam();"];
// NSString *heightStr = (NSString *)[webView stringByEvaluatingJavaScriptFromString:#"document.documentElement.innerText;"];
// NSString *heightStr = [webView stringByEvaluatingJavaScriptFromString:#"document.all[0].innerHTML"];
NSURL *requestURL = [[self.webViewIphone request] URL];
NSError *error;
NSString *heightStr = [NSString stringWithContentsOfURL:requestURL
encoding:NSASCIIStringEncoding
error:&error];
debug(#"HTml string %#",heightStr);
int height = [heightStr length];
CGFloat screenHeight = webView.scrollView.contentSize.height;
debug(#"%f",screenHeight);
int pages = ceil(height / screenHeight);
NSMutableData *pdfData = [NSMutableData data];
UIGraphicsBeginPDFContextToData(pdfData, webView.bounds, nil);
CGRect frame = [webView frame];
for (int i = 0; i < pages; i++) {
// Check to screenHeight if page draws more than the height of the UIWebView
if ((i+1) * screenHeight > height) {
CGRect f = [webView frame];
f.size.height -= (((i+1) * screenHeight) - height);
[webView setFrame: f];
}
UIGraphicsBeginPDFPage();
CGContextRef currentContext = UIGraphicsGetCurrentContext();
// CGContextTranslateCTM(currentContext, 72, 72); // Translate for 1" margins
[[[webView subviews] lastObject] setContentOffset:CGPointMake(0, screenHeight * i) animated:NO];
[webView.layer renderInContext:currentContext];
}
UIGraphicsEndPDFContext();
// Retrieves the document directories from the iOS device
NSArray* documentDirectories = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask,YES);
NSString* documentDirectory = [documentDirectories objectAtIndex:0];
NSString* documentDirectoryFilename = [documentDirectory stringByAppendingPathComponent:aFilename];
// instructs the mutable data object to write its context to a file on disk
[pdfData writeToFile:documentDirectoryFilename atomically:YES];
NSData *dataTemp = [NSData dataWithContentsOfFile:documentDirectoryFilename];
return dataTemp;
}
NSString *docPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
NSString *fileName =[docPath stringByAppendingPathComponent:[NSString stringWithFormat:#"%#.xlsx",downloadedfilename]];
[[NSFileManager defaultManager] createFileAtPath:reportName contents:receivedData attributes:nil];
NSURL *url = [NSURL fileURLWithPath:fileName];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
[webView loadRequest:request];
you can load xlsx,pdf, word document files like above code
This is used for the loading th pdf file into UIWebview.
UIWebView *webView = [[UIWebView alloc] initWithFrame:CGRectMake(10, 10, 200, 200)];
NSURL *targetURL = [NSURL URLWithString:#"http://developer.apple.com/iphone/library/documentation/UIKit/Reference/UIWebView_Class/UIWebView_Class.pdf"];
NSURLRequest *request = [NSURLRequest requestWithURL:targetURL];
[webView loadRequest:request];
[self.view addSubview:webView];
[webView release];
I have loaded a PDF file in a UIWebView from the resource bundle.
Now, I am not able to zoom/pinch the PDF file.
I found the below 2 relevant links, but none of the answers are marked as correct -
How to zoom webView with pdf file
Enable zooming/pinch on UIWebView
How to make the PDF zoomable/pinchable which has been loaded in a UIWebView from the resource bundle, Will the below solution work ?
Problem with pdf while opening in UIWebView
Thanks for your help.
In your WebView on Interface Builder add check to Scale Page To Fit and you enable a Pinch ZoomIn ZoomOut ;)
Or if you want to lad better your PDF try to Look this code:
- (void)viewDidLoad
{
[super viewDidLoad];
[webView loadRequest:[NSURLRequest requestWithURL:#"http:pdfURL"]];
NSString *path = [[NSBundle mainBundle] pathForResource:#"yourPDFFile" ofType:#"pdf"];
NSURL *url = [NSURL fileURLWithPath:path];
NSURLRequest * request = [NSURLRequest requestWithURL:url];
[webView loadRequest:request];
//--------------AND HERE USE SCALE PAGE TO FIT------------------//
[webView setScalesPageToFit:YES];
}
Hope this help you.
//Try like this
NSString *urlstr=#"www.example.com/yy.pdf";
web=nil;
web=[[UIWebView alloc] initWithFrame:CGRectMake(0, 98, 320, 367)];
web.delegate=self;
[self.view addSubview:web];
[web loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:urlstr]]];
UIPinchGestureRecognizer *pgr = [[UIPinchGestureRecognizer alloc]
initWithTarget:self action:#selector(handlePinch:)];
pgr.delegate = self;
[web addGestureRecognizer:pgr];
// Target Action
- (IBAction)handlePinch:(UIPinchGestureRecognizer *)recognizer
{
recognizer.view.transform = CGAffineTransformScale(recognizer.view.transform, recognizer.scale, recognizer.scale);
recognizer.scale = 1;
}
Before this add UIGestureRecognizerDelegate in .h. Hope it will helps you..
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask,YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSFileManager *fileManager = [NSFileManager defaultManager];
if ([fileManager fileExistsAtPath:documentsDirectory])
{
NSURL *url = [NSURL fileURLWithPath:strFileName];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
[webView setScalesPageToFit:YES];
[webview loadRequest:request];
}