I have a NSMutableData which contains pdf data. I want to delete certain pages from the pdf and return the pdf. I have tried creating the CGPDFContext, CGPDFPageRef, etc, but nothing really worked out. I have the below code, Can someone help me to fill the 3 steps.
-(NSMutableData *)deletePagesofPDF:(NSMutableData *)data withStartPage:(int)startpage withEndPage:(int)endpage{
NSData *data1 = data;
CFDataRef myPDFData = (__bridge CFDataRef)data1;
CGDataProviderRef provider = CGDataProviderCreateWithCFData(myPDFData);
CGPDFDocumentRef pdf = CGPDFDocumentCreateWithProvider(provider);
//step 1 delete pages from startpage to endpage.
//step 2 save pdf
//step 3 convert pdf back to NSMutabledata
return data;
}
Edit 1
I have decided to change my strategy. Instead of deleting the pages, i am now creating a new pdf with only the pages i require from another PDF. Please see the code below, somehow it crashes while creating the pdf context. error is : address doesn't contain a section that points to a section in a object file. I could not go past creating the context. Please correct me if there is something wrong after creating the context.
-(void)saveNSDataToPDFFile:(NSMutableData *)data{
NSData *data1 = data;
CFDataRef myPDFData = (__bridge CFDataRef)data1;
CGDataProviderRef provider = CGDataProviderCreateWithCFData(myPDFData);
CGPDFDocumentRef pdf = CGPDFDocumentCreateWithProvider(provider);
CGPDFPageRef newPage = CGPDFDocumentGetPage(pdf, 2);
NSMutableData *pdfData = [[NSMutableData alloc] init];
CGRect mediaBox = CGRectMake(0, 0, 850, 1100);
CGContextRef pdfContext = CGPDFContextCreate((__bridge CGDataConsumerRef)(pdfData),&mediaBox,NULL);
CGPDFContextBeginPage (pdfContext,nil);
CGContextDrawPDFPage(pdfContext, newPage);
CGPDFContextClose(pdfContext);
[pdfData writeToFile:[self getDBPathPDf:@"Rajashekar.pdf"] atomically:YES];
}
EDIT 2
Sorry about my long post. I can save the pdf file now without crashing but i cannot see the data inside the pdf. It just shows a medium sized box with "PDF" written inside it. Where am i going wrong?
-(void)saveNSDataToPDFFile:(NSMutableData *)data{
NSData *data1 = data;
CFDataRef myPDFData = (__bridge CFDataRef)data1;
CGDataProviderRef provider = CGDataProviderCreateWithCFData(myPDFData);
CGPDFDocumentRef pdf = CGPDFDocumentCreateWithProvider(provider);
CGPDFPageRef newPage = CGPDFDocumentGetPage(pdf, 2);
NSMutableData *pdfData = [[NSMutableData alloc] init];
CGRect mediaBox = CGRectMake(0, 0, 850, 1100);
CGDataConsumerRef consumer = CGDataConsumerCreateWithCFData((__bridge CFMutableDataRef)pdfData);
CGContextRef pdfContext = CGPDFContextCreate(consumer,&mediaBox,NULL);
if (pdfContext)
{
CGPDFContextBeginPage (pdfContext,nil);
CGContextDrawPDFPage(pdfContext, newPage);
CGPDFContextClose(pdfContext);
[pdfData writeToFile:[self getDBPathPDf:@"Rajashekar.pdf"] atomically:YES];
}
}
EDIT 3
Its working....:) i forgot to CGPDFContextEndPage(pdfContext); before i closed the context.