![](/img/trans.png)
[英]How to convert AVAudioPCMBuffer to NSData in Objective-C?
[英]How to generate pdf using NSData or using data bytes objective 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<UInt8>(data.bytes), data.length) else { return nil}
let cgDataProvider = CGDataProviderCreateWithCFData(cfData)
guard let cgPDFDocument = CGPDFDocumentCreateWithProvider(cgDataProvider) else { return nil }
希望以上有所帮助
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.