Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to generate pdf using NSData or using data bytes objective c?

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];


}

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.

like image 505
Nitesh Meshram Avatar asked May 29 '13 06:05

Nitesh Meshram


1 Answers

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];
}

Summary: get NSData from pdf file path

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

write NSData to pdf file

[pdfData writeToFile:pathToFile2 atomically:YES];
like image 114
Paras Joshi Avatar answered Oct 05 '22 22:10

Paras Joshi