在iPhone上的Safari中打开PDF

在iPhone上的Safari中打开PDF

问题描述:

是否可以从Safari的网站打开PDF以将其保存到本地磁盘?

Is it possible to open a PDF from a website in Safari in order to save it to local disk?

可以使用 NSURL类下载pdf文件到您的文档目录,绕过需要在Safari中打开它(然后终止您自己的应用程序)。

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 使得显示外部PDF和本地文件变得非常容易指向正确的文件路径),因此您甚至可以将PDF下载到您的文档文件夹,然后稍后从本地缓存中显示它。

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.

在下面添加了一些示例代码

对于更简单的示例,您可能会发现这对于您的应用程序是可以接受的;这将下载文件到您的文档文件夹,但使用一个阻塞函数( initWithContentsOfURL ),所以你可能遇到大文件/慢连接的问题:

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

为了给你一个基本的构建示例,下面的代码足以显​​示一个PDF文件

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

}

如果您要直接从网站而不是本地文件),那么您可以使 pdfPath 包含该文件的完整URL。

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.