views:

120

answers:

1

Hello guys!

Here's my code for getting the pages from a pdf document and create a pdf document with each page:

- (void)getPages {
NSString *pathToPdfDoc = [[NSBundle mainBundle] pathForResource:@"security" ofType:@"pdf"];
NSURL *pdfUrl = [NSURL fileURLWithPath:pathToPdfDoc];

CGPDFDocumentRef document = CGPDFDocumentCreateWithURL((CFURLRef)pdfUrl);

size_t numberOfPages = CGPDFDocumentGetNumberOfPages(document);

for (size_t i = 0; i < numberOfPages; i++) {
    CGPDFPageRef page = CGPDFDocumentGetPage(document, 0);

    CGRect pageRect = CGPDFPageGetBoxRect(page, kCGPDFMediaBox);

    NSString *filename = [NSString stringWithFormat:@"./security%d.pdf", i];

    CFStringRef path = CFStringCreateWithCString (NULL, [filename UTF8String], kCFStringEncodingUTF8);
    CFURLRef url = CFURLCreateWithFileSystemPath (NULL, path, kCFURLPOSIXPathStyle, 0);
    CFRelease (path);

    CFMutableDictionaryRef myDictionary = CFDictionaryCreateMutable(NULL, 0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks);
    CFDictionarySetValue(myDictionary, kCGPDFContextTitle, CFSTR("My PDF File"));
    CFDictionarySetValue(myDictionary, kCGPDFContextCreator, CFSTR("My Name"));

    CGContextRef pdfContext = CGPDFContextCreateWithURL(url, &pageRect, myDictionary);
    CFRelease(myDictionary);
    CFRelease(url);

    CGContextBeginPage(pdfContext, &pageRect);
    MyDrawPDFPageInRect(pdfContext, page, kCGPDFMediaBox, pageRect, 0, true);
    CGContextEndPage (pdfContext);
    CGContextRelease (pdfContext);
}

CGPDFDocumentRelease(document);
}

void MyDrawPDFPageInRect(CGContextRef context, CGPDFPageRef page, CGPDFBox box, CGRect rect, int rotation, bool preserveAspectRatio) {
CGAffineTransform m;

m = CGPDFPageGetDrawingTransform(page, box, rect, rotation, preserveAspectRatio);
CGContextSaveGState(context);
CGContextConcatCTM(context, m);
CGContextClipToRect(context, CGPDFPageGetBoxRect (page, box));
CGContextDrawPDFPage(context, page);
CGContextRestoreGState(context);
}

The problem is that the pages appears in the filesystem, but they are empty. Any idea why is that?

+2  A: 

PDF pages are numbered from 1. So this line:

    CGPDFPageRef page = CGPDFDocumentGetPage(document, 0);

gives you a null page, which in turn gives you an empty page rect, and from then on you're drawing nothing into nothing. Moreover, it's the same nothing each time, because you're always getting page 0 rather than moving through the pages.

What you want instead is to make the loop variable go from 1, and use it to get the pages:

for ( size_t i = 1; i <= numberOfPages; i++ ) {
    CGPDFPageRef page = CGPDFDocumentGetPage(document, i);

Everything else should work as is, I think.

walkytalky
I would cry... I didn't see that I wrote there a 0 instead of the for variable... Thank you very much man! And also for the advise that pdf pages start from 1.
Infinity