macos - 如何将 NSView 正确绘制到 PDF 上下文?

标签 macos cocoa drawing quartz-graphics cgpdfcontext

我已经有了 NSView ,并为此 NSView 添加了一些 subview ,它们是 NSView 的子类(名为:Square)。不同位置的正方形为 50x50。我想用背景颜色 RedBlue 渲染这个 NSView,并使用白色背景,如屏幕截图所示。

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);

我得到的只是空白的 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/

相关文章:

linux - 在调用自定义代码的 Mac OS X 和 Linux 中创建 "virtual"路径 (/bla)

cocoa - 在 Safari 中打开 WebView 链接

objective-c - NSTask 阻塞主线程

c# - 绘制低不透明度的填充矩形

c++ - Mac OS X 中的 sem_getvalue() 功能障碍 - C++

java - 在 Mac 上设置 IntelliJ 和 GlassFish

ios - Program 和 ProgramArguments 有什么不同

cocoa - 如何迭代 UIImage 的所有像素?

iOS 在 UIView 中绘制像素

Java 2d drawLine 对于长线来说很慢