如何使用NSData生成pdf或使用数据字节目标c?

嗨,我想使用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 …我从下面的链接中获取下面的代码

 NSString *string=[NSString stringWithFormat:@"%@.pdf",[yourArray objectAtIndex:pageIndex]]; [controller1 addAttachmentData:pdfData mimeType:@"application/pdf" fileName:string]; [self presentModalViewController:controller1 animated:YES]; [controller1 release]; //to convert pdf to NSData NSString *pdfPath = [documentsDirectory stringByAppendingPathComponent:@"test.pdf"]; NSData *myData = [NSData dataWithContentsOfFile:pdfPath]; //to convert NSData to pdf NSData *data = //some nsdata CFDataRef myPDFData = (CFDataRef)data; CGDataProviderRef provider = CGDataProviderCreateWithCFData(myPDFData); CGPDFDocumentRef pdf = CGPDFDocumentCreateWithProvider(provider); -(IBAction)saveasPDF:(id)sender{ NSString *string=[NSString stringWithFormat:@"%@.pdf",[yourArray objectAtIndex:pageIndex]]; [controller1 addAttachmentData:pdfData mimeType:@"application/pdf" fileName:string]; [self presentModalViewController:controller1 animated:YES]; [pdfData writeToFile:[self getDBPathPDf:string] atomically:YES]; } -(NSString *) getDBPathPDf:(NSString *)PdfName { NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory , NSUserDomainMask, YES); NSString *documentsDir = [paths objectAtIndex:0]; return [documentsDir stringByAppendingPathComponent:PdfName]; } 

摘要 :从pdf文件路径获取NSData

 NSData *pdfData = [NSData dataWithContentsOfFile:pathToFile1]; NSLog(@"pdfData= %d", pdfData != nil); 

将NSData写入pdf文件

 [pdfData writeToFile:pathToFile2 atomically:YES]; 

@ChallengerGuy(如果您仍在为CGPDFDocument寻找Swift 2方法)

 //to convert data of type NSData guard let cfData = CFDataCreate(kCFAllocatorDefault, UnsafePointer(data.bytes), data.length) else { return nil} let cgDataProvider = CGDataProviderCreateWithCFData(cfData) guard let cgPDFDocument = CGPDFDocumentCreateWithProvider(cgDataProvider) else { return nil } 

希望以上有所帮助