Skip to content

Instantly share code, notes, and snippets.

@yaakov-h
Forked from samdmarshall/images2pdf.mm
Last active December 10, 2015 13:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yaakov-h/4438810 to your computer and use it in GitHub Desktop.
Save yaakov-h/4438810 to your computer and use it in GitHub Desktop.
#import <Foundation/Foundation.h>
#import <AppKit/AppKit.h>
int main (int argc, const char * argv[]) {
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
if (argc == 2) {
NSString *folderPath = [[NSString stringWithFormat:@"%s",argv[1]] stringByExpandingTildeInPath];
BOOL isFolder;
if ([[NSFileManager defaultManager] fileExistsAtPath:folderPath isDirectory:&isFolder]) {
if (isFolder) {
NSArray *contents = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:folderPath error:nil];
NSMutableData* outputData = [[NSMutableData alloc] init];
CGDataConsumerRef dataConsumer = CGDataConsumerCreateWithCFData((CFMutableDataRef)outputData);
CGContextRef pdfContext = CGPDFContextCreate(dataConsumer, NULL, NULL);
CFRelease(dataConsumer);
for (NSString *path in contents) {
NSString *itemPath = [folderPath stringByAppendingPathComponent:path];
BOOL directoryItemIsFolder;
if ([[NSFileManager defaultManager] fileExistsAtPath:itemPath isDirectory:&directoryItemIsFolder]) {
if (!directoryItemIsFolder) {
if (UTTypeConformsTo((CFStringRef)[[NSWorkspace sharedWorkspace] typeOfFile:itemPath error:nil],kUTTypeImage)) {
CGImageSourceRef pageSource = CGImageSourceCreateWithURL((CFURLRef)[NSURL fileURLWithPath:itemPath], NULL);
CGImageRef pageImage = CGImageSourceCreateImageAtIndex(pageSource, 0, NULL);
CGRect pageSize = CGRectMake(0, 0, CGImageGetWidth(pageImage), CGImageGetHeight(pageImage));
CGContextBeginPage(pdfContext, &pageSize);
CGContextDrawImage(pdfContext, pageSize, pageImage);
CGImageRelease(pageImage);
CFRelease(pageSource);
CGContextEndPage(pdfContext);
}
}
}
}
CGPDFContextClose(pdfContext);
CGContextRelease(pdfContext);
NSString* documentPath = [folderPath stringByAppendingPathComponent:[NSString stringWithFormat:@"%@ - generated.pdf",[folderPath lastPathComponent]]];
[outputData writeToFile:documentPath atomically:YES];
[outputData release];
}
}
} else {
NSLog(@"Please supply only the path to the folder.");
}
[pool drain];
return 0;
}
// Sent from my iPhone
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment