6

嗨,我想使用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。

4

2 回答 2

8

您可以使用以下代码转换NSDataPDF...我从此链接获得以下代码

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];
于 2013-05-29T06:19:26.713 回答
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 }

希望以上有所帮助

于 2016-04-16T19:11:44.730 回答