将pdf文件保存在设备中 [英] save pdf file in device
问题描述
我在程序中生成了一个pdf文件,并且在这里:
I generated a pdf file in my program and I have it here :
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *file = [documentsDirectory stringByAppendingFormat:@"/CEX.pdf"];
NSData *data = [NSData dataWithContentsOfFile:file];
我知道如何将照片保存在照片库中,但不知道该如何处理pdf文件以及如何以及在何处将其保存在设备中.谁能帮我吗? :)
I know how to save photos in the photo gallery but have no idea what should I do with pdf file and how and where to save it in the device. Can anyone help me please ?! :)
推荐答案
您发布的代码用于从Documents
目录读取现有的PDF文件.
The code you posted is for reading an existing PDF file from the Documents
directory.
如果要编写PDF,则需要获取代表PDF的NSData
对象,创建文件的路径,然后使用NSData writeToFile:options:error:
方法将数据保存到文件中.
If you want to write the PDF, you need to get the NSData
object representing the PDF, create a path to the file, then use the NSData writeToFile:options:error:
method to save the data to the file.
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);
}
顺便说一句-在您的原始代码中,替换:
BTW - in your original code, replace:
NSString *file = [documentsDirectory stringByAppendingFormat:@"/CEX.pdf"];
具有:
NSString *file = [documentsDirectory stringByAppendingPathComponent:@"CEX.pdf"];
除非您确实有要处理的字符串格式,否则请不要使用字符串格式.
Don't use string formats unless you really have a string format to process.
这篇关于将pdf文件保存在设备中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!