1
votes

Is there any way to render a layer hosting NSView (as it appears onscreen) to a PDF or bitmap file without implementing each CALayer's –drawInContext: method (or similarly, each layer's delegate's -(void)drawLayer:inContext: method)? I just want the contents of the NSView exactly as they appear with minimal extra drawing code.

I've read numerous sources that say that to render to a PDF, you have to implement -drawInContext:, which makes sense if you're dealing with a custom layer subclass (otherwise, how else would it know what to draw), but I want to render layers that "just work" when you add them to a view, such as CATextLayer or CAShapeLayer. It seems completely redundant to have to rewrite the code for a CATextLayer telling it how to draw itself when it's clearly fully capable of doing that to the screen.

Have I missed something obvious?

1

1 Answers

4
votes

I have successfully written a view's layer hierarchy to a PDF using the following code:

- (void)renderToPath:(NSString *)filePath
{
    NSImage *image = [[NSImage alloc] initWithSize:self.bounds.size];
    [image lockFocus];
    [self.layer renderInContext:[NSGraphicsContext currentContext].CGContext];
    [image unlockFocus];

    NSImageView *tempImageView = [[NSImageView alloc] initWithFrame:self.bounds];
    tempImageView.image = image;
    NSData *pdf = [tempImageView dataWithPDFInsideRect:self.bounds];
    [pdf writeToFile:filePath atomically:YES];
}

Here's a sample project.