3

I am having problem with PDF conversion to images. I would like to create an image file for every page in PDF document.

This is the code I am using and works fine. Every page gets converted into the image, but I have problem with image resolution. I don't know how to set the resolution of the output images. Can someone help me out?

NSData *pdfData = [NSData dataWithContentsOfURL:[NSURL URLWithString:@"http://localhost/test/test.pdf"]];


NSPDFImageRep *img = [NSPDFImageRep imageRepWithData:pdfData]; 
 NSFileManager *fileManager = [NSFileManager defaultManager];
 int count = [img pageCount]; 
 for(int i = 0 ; i < count ; i++) { 
  [img setCurrentPage:i]; 
  NSImage *temp = [[NSImage alloc] init]; 
  [temp addRepresentation:img]; 
  NSBitmapImageRep *rep = [NSBitmapImageRep imageRepWithData:[temp TIFFRepresentation]]; 
  NSData *finalData = [rep representationUsingType:NSJPEGFileType properties:nil]; 
  NSString *pageName = [NSString stringWithFormat:@"Page_%d.jpg", [img currentPage]]; 
  [fileManager createFileAtPath:[NSString stringWithFormat:@"%@/%@", @"/Users/mac/Desktop/", pageName] contents:finalData attributes:nil];
 }

Thanks a lot!

mipadi
  • 398,885
  • 90
  • 523
  • 479
Primoz Rome
  • 10,379
  • 17
  • 76
  • 108

2 Answers2

2

Since NSPDFImageRep is a subclass of NSImageRep, couldn't you use the [NSImageRep drawInRect:] method?

Link: http://developer.apple.com/mac/library/documentation/cocoa/reference/ApplicationKit/Classes/NSImageRep_Class/Reference/Reference.html#//apple_ref/doc/uid/20000346-drawInRect_

refulgentis
  • 2,624
  • 23
  • 37
  • I don't think that would work since I need to call [NSPDFImageRep imageRepWithData:pdfData], which creates and returns an NSPDFImageRep object initialized with the specified PDF data. If I would use [NSImageRep drawInRect:], how would I get PDF page to draw into this rect? – Primoz Rome Dec 13 '09 at 18:32
  • 1
    For me it looks like this approach is working fine. This is the code: NSRect bounds = pdfImageRep.bounds; CGFloat factor = 4.; NSRect rect = NSMakeRect(0, 0, bounds.size.width * factor, bounds.size.height * factor); NSImage *image = [[NSImage alloc] initWithSize:rect.size]; [image lockFocus]; [pdfImageRep drawInRect:rect]; [image unlockFocus]; – Holtwick Feb 20 '13 at 18:29
2

The simplest way would be to use the ImageIO framework. Feed the PDF data to an image source to get a CGImage; feed that object to an image destination to generate (and optionally save in the same step) the JPEG data. In the latter step, you can specify the resolution among the image properties; see “Individual Image Properties” in the documentation.

Don't forget to finalize your destination. It's vital.

Peter Hosey
  • 95,783
  • 15
  • 211
  • 370