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?

有帮助吗?

解决方案

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.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top