Hihi, I am trying to save pdf files as jpg files. I have a number of urls to query from and these url links are all 1 page pdf files.
var path = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] as! String
let urlRequest = NSURLRequest(URL: NSURL(string: downloadUrl[index])!)
NSURLConnection.sendAsynchronousRequest(urlRequest, queue: NSOperationQueue.mainQueue()) { (response, data, error) -> Void in
var savePath = path.stringByAppendingPathComponent(file_name + ".jpg")
if let httpResponse = response as? NSHTTPURLResponse {
if let contentType = httpResponse.allHeaderFields["Content-Type"] as? NSString {
let fileType = contentType.componentsSeparatedByString("/").last! as! String
if fileType == "pdf" {
// convert to jpg before saving!
NSFileManager.defaultManager().createFileAtPath(savePath, contents: convertedData, attributes: nil)
} else {
NSFileManager.defaultManager().createFileAtPath(savePath, contents: data, attributes: nil)
}
self.tableView.reloadData()
}
}
}
So I am trying to find a solution to convert the data, which is the NSData for the pdf file, into the NSData format for an image file, so that I can save it via the function createFileAtPath with the image NSData as one of the arguments.
Thanks in advance!
UPDATE:
With reference to Rendering a CGPDFPage into a UIImage and David's (thx!) link,
// replace "//convert to jpg before saving!" in the code snippet above
var pdfData = data as CFDataRef
var provider:CGDataProviderRef = CGDataProviderCreateWithCFData(pdfData)
var pdfDoc:CGPDFDocument = CGPDFDocumentCreateWithProvider(provider)
var pdfPage:CGPDFPage = CGPDFDocumentGetPage(pdfDoc, 1)
var pageRect:CGRect = CGPDFPageGetBoxRect(pdfPage, kCGPDFMediaBox)
pageRect.size = CGSizeMake(pageRect.size.width, pageRect.size.height)
println("\(pageRect.width) by \(pageRect.height)")
UIGraphicsBeginImageContext(pageRect.size)
var context:CGContextRef = UIGraphicsGetCurrentContext()
CGContextSaveGState(context)
CGContextTranslateCTM(context, 0.0, pageRect.size.height)
CGContextScaleCTM(context, 1.0, -1.0)
CGContextConcatCTM(context, CGPDFPageGetDrawingTransform(pdfPage, kCGPDFMediaBox, pageRect, 0, true))
CGContextDrawPDFPage(context, pdfPage)
CGContextRestoreGState(context)
let pdfImage:UIImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
let convertedData:NSData = UIImagePNGRepresentation(pdfImage)
convertedData.writeToFile(savePath, atomically: true)
So the images got saved, but the resolution is bad..Upon further investigation, I found that the width and height of 'pageRect' is now lower than the dimension that it holds when open with GIMP at a ratio of about 0.72. The println statement shows this. This creates the pixelated image of the pdf file. Hmmmm any ideas what caused the dip in dimension conversion n how to solve it?