我已经有了 NSView
,并为此 NSView
添加了一些 subview ,它们是 NSView
的子类(名为:Square
)。不同位置的正方形为 50x50。我想用背景颜色 Red
或 Blue
渲染这个 NSView,并使用白色背景,如屏幕截图所示。
- (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);
我得到的只是空白的 PDF 文件。我怎样才能在pdfContext中正确绘制这个正方形?
最佳答案
您必须调用CGPDFContextClose要写入的 PDF 数据:
// ...
CGPDFContextEndPage(pdfContext);
// Close the PDF document
CGPDFContextClose(pdfContenxt);
CGContextRelease(pdfContext);
// ...
documentation请注意,关闭上下文会导致写入数据,这可能解释了为什么您在未关闭的情况下得到空白 PDF:
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.
关于macos - 如何将 NSView 正确绘制到 PDF 上下文?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14570937/