Is it possible to open a PDF from a website in Safari in order to save it to local disk?
You can use the NSURL class to download the pdf file to your documents directory, bypassing the need to open it in Safari (and subsequently terminating your own app).
UIWebView makes it nice and easy to display external PDFs as well as local files (just point the correct filepath at it), so you could even download the PDF to your documents folder and then display it from the local cache at a later date.
Added some sample code below
For a simpler example, you might find this is acceptable for your app; This will download the file to your documents folder but uses a blocking function (initWithContentsOfURL
), so you may run into problems with large files/slow connections:
(This code should be all you need, but you will probably want to create a function to handle this step/handle memory/check for errors etc)
//Grab the file from the URL
NSData *pdfData = [[NSData alloc] initWithContentsOfURL:[NSURL URLWithString:@"http://www.website.com/doc1.pdf"]];
// Put the data into a file in your Documents folder
NSString *docFolder = [[NSString alloc] initWithString:[[[[NSBundle mainBundle] resourcePath] stringByDeletingLastPathComponent] stringByAppendingPathComponent:@"Documents"]];
NSString *filePath = [resourceDocPath stringByAppendingPathComponent:@"doc1.pdf"];
[pdfData writeToFile:filePath atomically:YES];
To give you a basic sample to build from, the following code is enough to display a PDF file inside from your Documents folder in a webview:
-(void)viewDidLoad
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *pdfPath = [documentsDirectory stringByAppendingPathComponent:@"doc.pdf"];
// ...
webView.scalesPageToFit = YES;
webView.autoresizingMask = (UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight);
[webView loadRequest:[NSURLRequest requestWithURL:[NSURL fileURLWithPath:pdfPath isDirectory:NO]]];
}
Should you want to display the PDF directly from the website (rather than a local file) then you can have pdfPath
contain the full URL to the file instead.