Search code examples
cocoapdfnsimage

Extract NSImage from PDFPage with varying resolution


What is the best way to get an NSImage from a PDFPage object, with variable resolution?

I have a PDF file displayed in a PDFView and I need to capture the current page and store as an NSImage. Additionally, I need to be able to vary the resolution (DPI) of the page.

With this code, the resulting image is only 595x841 for an A4 page. I need higher resolution than this (up to 300DPI):

PDFPage *page = _pdfView.currentPage;
NSData *pageData = page.dataRepresentation;
NSImage *img = [[NSImage alloc] initWithData:pageData];

Solution

  • I finally managed to sort this out:

    CGFloat factor = 300/72; // Scale from 72 DPI to 300 DPI
    NSImage *img; // Source image
    NSSize newSize = NSMakeSize(img.size.width*factor, img.size.height*factor);
    NSImage *scaledImg = [[NSImage alloc] initWithSize:newSize];
    [scaledImg lockFocus];
    [[NSColor whiteColor] set];
    [NSBezierPath fillRect:NSMakeRect(0, 0, newSize.width, newSize.height)]; 
    NSAffineTransform *transform = [NSAffineTransform transform];
    [transform scaleBy:factor];
    [transform concat];
    [img drawAtPoint:NSZeroPoint fromRect:NSZeroRect operation:NSCompositeSourceOver fraction:1.0];
    [scaledImg unlockFocus];