如何使用NSData生成pdf或使用数据字节目标c? [英] How to generate pdf using NSData or using data bytes objective c?

查看:98
本文介绍了如何使用NSData生成pdf或使用数据字节目标c?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Hi I want to write pdf using NSData or using data bytes given by 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。

I am using this but it's not working it's give me error "It may be damaged or use a file format that Preview doesn’t recognize." on opening that pdf created by above code.

推荐答案

您可以将 NSData 转换为 PDF 使用以下代码...我从此链接获得以下代码

you can convert NSData to PDF with bellow code... I get the bellow Code From 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


Summary: get NSData from pdf file path

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

将NSData写入pdf文件

write NSData to pdf file

[pdfData writeToFile:pathToFile2 atomically:YES];

这篇关于如何使用NSData生成pdf或使用数据字节目标c?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆