Last active
November 4, 2015 10:13
-
-
Save mindboard/79d13966d5a71d87fa86 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import Foundation | |
import CoreFoundation | |
import CoreImage | |
let path = NSProcessInfo.processInfo().arguments[1] | |
let url:NSURL = NSURL(fileURLWithPath: path) as CFURLRef | |
let pdfDocument = CGPDFDocumentCreateWithURL(url) // CGPDFDocument | |
// | |
// save each page into png file. | |
// | |
let pageCount = CGPDFDocumentGetNumberOfPages(pdfDocument) | |
for index in 1...pageCount { | |
let page = CGPDFDocumentGetPage(pdfDocument, index) // CGPDFPage | |
let colorSpace = CGColorSpaceCreateDeviceRGB() // CGColorSpace | |
let bitmapInfo = CGImageAlphaInfo.PremultipliedFirst | |
let mediaBoxRect = CGPDFPageGetBoxRect(page, CGPDFBox.MediaBox) // CGRect | |
let w = Int( mediaBoxRect.size.width ) | |
let h = Int( mediaBoxRect.size.height ) | |
let context = CGBitmapContextCreate( | |
nil, | |
w, h, 8, 0, colorSpace, bitmapInfo.rawValue) | |
// よく分からないが上下反転しなくてよくなったってことかな? | |
/* | |
CGContextSaveGState(context) | |
CGContextTranslateCTM(context, 0.0, mediaBoxRect.size.height) | |
CGContextScaleCTM(context, 1, -1) | |
CGContextDrawPDFPage(context, page) | |
CGContextRestoreGState(context) | |
*/ | |
CGContextDrawPDFPage(context, page) | |
let image = CGBitmapContextCreateImage(context) //CGImageRef | |
let dataProvider = CGImageGetDataProvider( image ) // CGDataProviderRef | |
let data = CGDataProviderCopyData(dataProvider) | |
let imageType = kUTTypePNG | |
let savePngFilename = "page-" + String(index) + ".png" | |
let savePngFileUrl:NSURL = NSURL(fileURLWithPath: savePngFilename) as CFURLRef | |
let file = CGImageDestinationCreateWithURL( savePngFileUrl, imageType, 1, nil ) | |
print( file ) // CGImageDestination | |
let options: [NSString:AnyObject] = [ | |
kCGImagePropertyOrientation : 1, | |
kCGImagePropertyHasAlpha : true, | |
kCGImageDestinationLossyCompressionQuality : 0.80] | |
CGImageDestinationAddImage(file!, image!, options) | |
CGImageDestinationFinalize(file!) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment