/* * Extract pages as separate PDFs from a PDF file on Mac OS X * See http://gidden.net/tom/2009/01/27/extract-pdf-pages/ * * Copyright 2009 Tom Gidden * * Licensed under the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. You may obtain * a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or * implied. See the License for the specific language governing * permissions and limitations under the License. */ #import int main (int argc, const char * argv[]) { NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; // Get the document's URL. I've been lazy here and just used the last arg. // Other args are ignored. NSString *path = [NSString stringWithCString:argv[--argc]]; NSURL *url = [NSURL fileURLWithPath:path]; // Get the original document CGPDFDocumentRef document = CGPDFDocumentCreateWithURL((CFURLRef)url); // How many pages does it have? int pages = CGPDFDocumentGetNumberOfPages(document); // For each page: for(size_t pagenum=1; pagenum<=pages; pagenum++) { // Get the page as an object CGPDFPageRef page = CGPDFDocumentGetPage(document, pagenum); // Create a filename for the new PDF file. NSString *npath = [NSString stringWithFormat:@"./%04d.pdf", pagenum]; NSURL *nurl = [NSURL fileURLWithPath:npath]; // Get the page bounding area. Not sure if this is the right one, but it'll // do for my purposes CGRect pageRect = CGPDFPageGetBoxRect(page, kCGPDFMediaBox); // Create a new graphics context to paint the page into, using the new URL // to store it in CGContextRef newContext = CGPDFContextCreateWithURL ((CFURLRef)nurl, &pageRect, nil); // Draw the page from the original document into this new context. CGContextBeginPage(newContext, &pageRect); CGContextDrawPDFPage(newContext, page); CGContextEndPage(newContext); // Finish up. CGContextRelease(newContext); } [pool drain]; return 0; }