views:

226

answers:

1

hi, I want to create a new PDF file from the existing pdf document.That is I have one pdf file say "old.pdf" and from that user can select some pages and from those selected pages I want to create new pdf file say "temp1.pdf". Is it possible to create "temp1.pdf"? Plz help me and also provide some code example to do that. Thanks.

A: 

Hi, this is my demo code, you can try it. But this code have some problem. The new generated PDF occur garbled text, i still have no way to solve this problem (Have anyone can help?).

//old pdf
NSArray* old_PDF_paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString* old_PDF_documentsDirectory = [old_PDF_paths objectAtIndex:0];
NSString* old_PDF_ABSOLUTE_PATH = [old_PDF_documentsDirectory stringByAppendingPathComponent:@"old.pdf"];

//new generate pdf
NSArray* output_PDF_paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString* output_PDF_documentsDirectory = [output_PDF_paths objectAtIndex:0];
NSString* output_PDF_ABSOLUTE_PATH = [output_PDF_documentsDirectory stringByAppendingPathComponent:@"temp1.pdf"];
NSString* outpath = output_PDF_ABSOLUTE_PATH;

NSURL *url = [[NSURL alloc] initFileURLWithPath:old_PDF_ABSOLUTE_PATH];
CGPDFDocumentRef originalPDF = CGPDFDocumentCreateWithURL((CFURLRef)url);

// query for the number of pages
int ct = CGPDFDocumentGetNumberOfPages(originalPDF);

CGFloat width = 0.0f;
CGFloat height = 0.0f;

CGRect outRect = CGRectMake(0, 0, width, height);
CFURLRef outurl = CFURLCreateWithFileSystemPath (NULL, (CFStringRef)outpath,  kCFURLPOSIXPathStyle, 0);
CFMutableDictionaryRef myDictionary = CFDictionaryCreateMutable(NULL, 0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks); 

// create a context for drawing
CGContextRef context = CGPDFContextCreateWithURL ((CFURLRef)outurl, &outRect, myDictionary); // 5
CFRelease(myDictionary);

for(int i = 1; i <= ct; ++i) {
    //page render
    CGPDFPageRef pdfPage =  CGPDFDocumentGetPage(originalPDF, i);
    CGRect pageMediaBox = CGPDFPageGetBoxRect(pdfPage, kCGPDFMediaBox); 
    CGContextBeginPage (context, &pageMediaBox); 
    CGContextDrawPDFPage(context, pdfPage);
    CGContextEndPage (context); 
}

CGContextClosePath(context);
CGContextRelease(context);
Erwin
ok thanks for your help. I'll try this out and let u know.
jaynaiphone