How can i draw NSView correctly to PDF context?

1.3k views Asked by At

I've got NSView and to this NSViewI added some subviews which are subclass of NSView (named: Square). Squares are 50x50 on different positions. I want to render this NSViews with background color Red or Blue with this white background like on screenshot.

enter image description here

- (void)saveAsPDF
{

NSString *homeDirectory = NSHomeDirectory();
NSURL *fileURL = [NSURL fileURLWithPath:[homeDirectory stringByAppendingPathComponent:@"plik.pdf"]];

CGRect mediaBox = self.bounds;

CGContextRef pdfContext = CGPDFContextCreateWithURL((__bridge CFURLRef)(fileURL), &mediaBox, NULL);

CGPDFContextBeginPage(pdfContext, nil);

for (Square *square in squareGroup) {
    [square.layer renderInContext:pdfContext];
}

CGPDFContextEndPage(pdfContext);

CGContextRelease(pdfContext);

Only what i've got is blank PDF file. How can i draw this squares correctly in pdfContext?

1

There are 1 answers

2
Michael Robinson On BEST ANSWER

You must call CGPDFContextClose for the PDF data to be written:

// ...

CGPDFContextEndPage(pdfContext);

// Close the PDF document
CGPDFContextClose(pdfContenxt);

CGContextRelease(pdfContext);

// ...

The documentation notes that closing the context causes data to be written, which might explain why you're getting a blank PDF without closing:

After closing the context, all pending data is written to the context destination, and the PDF file is completed. No additional data can be written to the destination context after the PDF document is closed.