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

时间:2013-05-29 06:14:59

标签: iphone ios objective-c

您好我想使用NSData编写pdf或使用webservice提供的数据字节?

    -(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。

2 个答案:

答案 0 :(得分:8)

您可以使用以下代码将NSData转换为PDF ...我会从This link

获得以下代码
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];

答案 1 :(得分:3)

@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 }

希望以上帮助