【问题标题】:save pdf file in device将pdf文件保存在设备中
【发布时间】:2012-12-26 14:51:13
【问题描述】:

我在我的程序中生成了一个 pdf 文件,我把它放在这里:

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);

    NSString *documentsDirectory = [paths objectAtIndex:0];

    NSString *file = [documentsDirectory stringByAppendingFormat:@"/CEX.pdf"];
    NSData *data = [NSData dataWithContentsOfFile:file];

我知道如何将照片保存在照片库中,但不知道我应该如何处理 pdf 文件以及将其保存在设备中的方式和位置。谁能帮帮我?! :)

【问题讨论】:

    标签: iphone ios pdf save


    【解决方案1】:

    您发布的代码用于从Documents 目录中读取现有的 PDF 文件。

    如果要写PDF,需要获取代表PDF的NSData对象,创建文件路径,然后使用NSData writeToFile:options:error:方法将数据保存到文件中。

    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString *file = [documentsDirectory stringByAppendingPathComponent:@"MyDocument.pdf"];
    
    NSData *pdfData = ... // data representing your created PDF
    NSError *error = nil;
    if ([pdfData writeToFile:file options:NSDataWritingAtomic error:&error]) {
        // file saved
    } else {
        // error writing file
        NSLog(@"Unable to write PDF to %@. Error: %@", file, error);
    }
    

    顺便说一句 - 在您的原始代码中,替换:

    NSString *file = [documentsDirectory stringByAppendingFormat:@"/CEX.pdf"];
    

    与:

    NSString *file = [documentsDirectory stringByAppendingPathComponent:@"CEX.pdf"];
    

    除非您确实有要处理的字符串格式,否则不要使用字符串格式。

    【讨论】:

      猜你喜欢
      • 2021-11-08
      • 2020-01-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-12-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多