Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert PDF pages to images with COCOA

Tags:

split

pdf

cocoa

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!

like image 542
Primoz Rome Avatar asked Dec 10 '25 12:12

Primoz Rome


2 Answers

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_

like image 64
refulgentis Avatar answered Dec 13 '25 12:12

refulgentis


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.

like image 30
Peter Hosey Avatar answered Dec 13 '25 11:12

Peter Hosey



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!