Search code examples
iphoneobjective-ciospdfnsdata

How to convert a NSData to pdf in iPhone sdk?


Am converting a webpage as a pdf file. I did the following,

NSString *string=[NSString stringWithFormat:@"%@.pdf",[chapersArray objectAtIndex:pageIndex]];
[controller1 addAttachmentData:pdfData mimeType:@"application/pdf" fileName:string];
[self presentModalViewController:controller1 animated:YES];
[controller1 release];

Now how can i convert my NSData into pdf and save in my application memory? Kindly help me with sample codes or suggestions. Thanks all.


Solution

  • Am assuming you have your pdf in documents directory here. You can change it to where ever it actually is. Try this -

    //to convert pdf to NSData
    NSString *pdfPath = [documentsDirectory stringByAppendingPathComponent:@"test.pdf"]; 
    NSData *myData = [NSData dataWithContentsOfFile:pdfPath]; 
    

    Essentially using CGPDFDocumentCreateWithProvider you can convert NSData to pdf,

    //to convert NSData to pdf
    NSData *data               = //some nsdata
    CFDataRef myPDFData        = (CFDataRef)data;
    CGDataProviderRef provider = CGDataProviderCreateWithCFData(myPDFData);
    CGPDFDocumentRef pdf       = CGPDFDocumentCreateWithProvider(provider);
    

    Don't forget to CFRelease all unused data after you are done.