Skip to content

Instantly share code, notes, and snippets.

@typester
Created March 2, 2011 11:14
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save typester/850786 to your computer and use it in GitHub Desktop.
Save typester/850786 to your computer and use it in GitHub Desktop.
#import <Cocoa/Cocoa.h>
static NSString* dumpPNG(CGPDFPageRef page, NSURL* outDir) {
size_t num = CGPDFPageGetPageNumber(page);
assert(num > 0);
CGRect r = CGPDFPageGetBoxRect(page, kCGPDFTrimBox);
// 画質わるいから二倍にしてみるテスト
size_t scale = 2;
size_t w = r.size.width * scale;
size_t h = r.size.height * scale;
CGColorSpaceRef colorspace = CGColorSpaceCreateWithName(kCGColorSpaceGenericRGB);
CGContextRef ctx = CGBitmapContextCreate(
NULL, // 10.6+
w, h,
8, w * 4,
colorspace,
kCGImageAlphaNoneSkipFirst
);
CGColorSpaceRelease(colorspace);
CGAffineTransform trans = CGAffineTransformMakeScale(scale, scale);
CGContextConcatCTM(ctx, trans);
CGContextDrawPDFPage(ctx, page);
CGImageRef img = CGBitmapContextCreateImage(ctx);
assert(NULL != img);
NSBitmapImageRep* rep = [[NSBitmapImageRep alloc] initWithCGImage:img];
NSData* data = [rep representationUsingType:NSPNGFileType properties:[NSDictionary dictionary]];
[rep release];
NSString* outFile = [[outDir path] stringByAppendingPathComponent:[NSString stringWithFormat:@"%04d.png", num]];
BOOL success = [data writeToFile:outFile atomically:NO];
assert(YES == success);
CGImageRelease(img);
CGContextRelease(ctx);
return outFile;
}
int main(int argc, char** argv) {
NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init];
if (argc < 3) {
NSLog(@"Usage: %s input.pdf output_dir\n", argv[0]);
goto exit;
}
NSURL* inputFile = [NSURL fileURLWithPath:[NSString stringWithUTF8String:argv[1]]];
NSURL* outputDir = [NSURL fileURLWithPath:[NSString stringWithUTF8String:argv[2]] isDirectory:YES];
CGPDFDocumentRef pdf = CGPDFDocumentCreateWithURL((CFURLRef)inputFile);
assert(NULL != pdf);
size_t pages = CGPDFDocumentGetNumberOfPages(pdf);
size_t p;
for (p = 1; p <= pages; ++p) {
NSAutoreleasePool* poolin = [[NSAutoreleasePool alloc] init];
CGPDFPageRef page = CGPDFDocumentGetPage(pdf, p);
assert(NULL != page);
NSString* wrotePath = dumpPNG(page, outputDir);
NSLog(@"wrote: %@", wrotePath);
[poolin drain];
}
CGPDFDocumentRelease(pdf);
exit:
[pool drain];
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment