如何在iPhone SDK中将NSData转换为pdf?

正在将网页转换为PDF文件。 我做了以下,

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

现在我怎么可以将我的NSData转换成pdf并保存在我的应用程序内存? 请帮助我的示例代码或build议。 谢谢大家。

假设你在这里的文档目录中有你的pdf。 您可以将其更改为实际所在的位置。 尝试这个 –

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

本质上使用CGPDFDocumentCreateWithProvider可以将NSData转换为pdf,

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

不要忘记CFRelease完成后发布所有未使用的数据。

我得到这是一个简单的方法如下,

 -(IBAction)saveasPDF:(id)sender{ NSString *string=[NSString stringWithFormat:@"%@.pdf",[chapersArray 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]; } 

你可以尝试这个解决scheme:

 - (void)saveDataToPDF:(NSData *)pdfDocumentData
 {
     //创buildPDF文档参考
     CGDataProviderRef dataProvider = CGDataProviderCreateWithCFData((CFDataRef)pdfDocumentData);
     CGPDFDocumentRef document = CGPDFDocumentCreateWithProvider(dataProvider);

     //创buildpdf上下文
     CGPDFPageRef page = CGPDFDocumentGetPage(document,1);  //页面从1开始编号
     CGRect pageRect = CGPDFPageGetBoxRect(page,kCGPDFMediaBox);
     CFMutableDataRef mutableData = CFDataCreateMutable(NULL,0);

     //NSLog(@"w:%2.2f,h:%2.2f“,pageRect.size.width,pageRect.size.height);
     CGDataConsumerRef dataConsumer = CGDataConsumerCreateWithCFData(mutableData);
     CGContextRef pdfContext = CGPDFContextCreate(dataConsumer,&pageRect,NULL);


    如果(CGPDFDocumentGetNumberOfPages(document)> 0)
     {
         //将页面绘制到新的上下文中
         // page = CGPDFDocumentGetPage(document,1);  //页面从1开始编号

         CGPDFContextBeginPage(pdfContext,NULL);
         CGContextDrawPDFPage(pdfContext,page);
         CGPDFContextEndPage(pdfContext);
     }
    其他
     {
         NSLog(@“无法创build文档”);
     }

     CGContextRelease(pdfContext);  //将数据写入磁盘之前释放。

     //写入磁盘
     [(__bridge NSData *)mutableData writeToFile:@“/ Users / David / Desktop / test.pdf”primefaces:YES];

     //清理
     CGDataProviderRelease(数据提供程序);  //释放数据提供者
     CGDataConsumerRelease(dataConsumer);
     CGPDFDocumentRelease(文件);
     CFRelease(mutableData);
 }