Iphone 如何使用NSData或数据字节c生成pdf?
您好,我想使用Iphone 如何使用NSData或数据字节c生成pdf?,iphone,ios,objective-c,Iphone,Ios,Objective C,您好,我想使用NSData或使用webservice提供的数据字节来编写pdf -(NSData *)saveData:(NSData*)fileData fileName:(NSString *)fileName fileType:(NSString *)fileType { NSFileManager *fileManager = [NSFileManager defaultManager]; NSArray *paths = NSSearchPathForDirec
NSData
或使用webservice提供的数据字节来编写pdf
-(NSData *)saveData:(NSData*)fileData fileName:(NSString *)fileName fileType:(NSString *)fileType
{
NSFileManager *fileManager = [NSFileManager defaultManager];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory , NSUserDomainMask, YES);
NSString *documentsDir = [paths objectAtIndex:0];
NSString *filePath = [NSString stringWithFormat:@"%@/%@.%@",documentsDir,fileName,fileType];
NSData* downloadData = [NSData dataWithData:fileData];
[fileManager createFileAtPath:filePath contents:downloadData attributes:nil];
}
我用这个,但它不工作,它给我的错误“它可能被损坏或使用的文件格式,预览不识别。”打开上述代码创建的pdf 您可以使用下面的代码将
NSData
转换为PDF
。。。我从你那里得到了下面的代码
摘要: 从pdf文件路径获取NSData
NSData *pdfData = [NSData dataWithContentsOfFile:pathToFile1];
NSLog(@"pdfData= %d", pdfData != nil);
将NSData写入pdf文件
[pdfData writeToFile:pathToFile2 atomically:YES];
@ChallengerGuy(如果您仍在寻找CGPDFDocument的Swift 2方法)
//转换NSData类型的数据
guard let cfData=CFDataCreate(kcfalocatordefault,UnsafePointer(data.bytes),data.length)else{return nil}
让cgDataProvider=CGDataProviderCreateWithCFData(cfData)
guard let cgPDFDocument=CGPDFDocumentCreateWithProvider(cgDataProvider)else{return nil}
希望以上内容有所帮助使用
NSData
的writeToFile:atomicaly:
比通过NSFileManager要好得多。数据是否已经是PDF格式,或者您是否正在寻找将其他数据转换为PDF的方法?你能试着用十六进制编辑器检查你的文件吗。您很可能会知道数据的格式。您也可以使用文件
命令行工具来确定某个文件的真实类型。@RaphaelSchweikert-是的,它是pdf格式的..您知道如何…?它是否在预览之外的任何其他PDF查看器中打开?@ParasJoshi,我试图使用“writeToFile:”保存该文件,但它没有在Preview.app中打开该文件。如何将上述CGPDFDocumentRef对象保存到pdf文件有任何帮助吗有人有Swift 2的帮助吗?
[pdfData writeToFile:pathToFile2 atomically:YES];
//to convert data of type NSData
guard let cfData = CFDataCreate(kCFAllocatorDefault, UnsafePointer<UInt8>(data.bytes), data.length) else { return nil}
let cgDataProvider = CGDataProviderCreateWithCFData(cfData)
guard let cgPDFDocument = CGPDFDocumentCreateWithProvider(cgDataProvider) else { return nil }