在IOS中本地保存pdf

时间:2014-03-27 08:44:30

标签: ios quartz-2d

您好我在IOS中使用Quartz框架创建了pdf文件。需要在本地文件夹中下载该pdf文件,比如在simulator中保存图像。任何一个告诉我如何执行此操作。

我创建pdf的代码

     -(NSString*)getPDFFileName
     {
     NSString* fileName = @"Invoice.PDF";

     NSArray *arrayPaths =
     NSSearchPathForDirectoriesInDomains(
                                    NSDocumentDirectory,
                                    NSUserDomainMask,
                                    YES);
     NSString *path = [arrayPaths objectAtIndex:0];
     NSString* pdfFileName = [path stringByAppendingPathComponent:fileName];

     return pdfFileName;

    }

    -(void)showPDFFile


    {
    NSString* fileName = @"Invoice.PDF";

    NSArray *arrayPaths =
    NSSearchPathForDirectoriesInDomains(
                                    NSDocumentDirectory,
                                    NSUserDomainMask,
                                    YES);
    NSString *path = [arrayPaths objectAtIndex:0];
    NSString* pdfFileName = [path stringByAppendingPathComponent:fileName];

    UIWebView* webView = [[UIWebView alloc] initWithFrame:CGRectMake(0, 0, 320, 480)];

    NSURL *url = [NSURL fileURLWithPath:pdfFileName];
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    [webView setScalesPageToFit:YES];
    [webView loadRequest:request];

    [self.view addSubview:webView];    
     }

  - (void)viewDidLoad
   {
  NSString* fileName = [self getPDFFileName];

  [PDFRenderer drawPDF:fileName];
  [self showPDFFile];

  [super viewDidLoad];
} 

提前感谢..

2 个答案:

答案 0 :(得分:2)

这将满足您的需求。

    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectoryPath = [paths objectAtIndex:0];
    NSString *pdfDirectoryString = [NSString stringWithFormat:@"%@/YOUR_FILE_NAME", documentsDirectoryPath];

    NSError *error = nil;
    if (![YOUR_PDF_DATA writeToFile:pdfDirectoryString options:NSDataWritingAtomic error:&error])
        NSLog(@"Error: %@", [error localizedDescription]);

答案 1 :(得分:0)

试试这个

用于在文档目录中保存PDF

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSData *data = [PDFImageConverter convertImageToPDF:screenShot]; // convert PDF to data
NSString *path = [NSString stringWithFormat:@"%@/%@",[docArr objectAtIndex:0],[NSString stringWithFormat:@"userDetails.pdf"]];
[data writeToFile:path atomically:NO];

在网页视图中检索和显示

NSArray     *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString    *documentsDirectory = [paths objectAtIndex:0];

NSString *pdfPathString =[NSString stringWithFormat:@"%@",[documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:@"userDetails.pdf"]]];
NSURL *targetURL = [NSURL fileURLWithPath:pdfPathString];
NSURLRequest *request = [NSURLRequest requestWithURL:targetURL];
[contentWebview loadRequest:request];