Reputation: 4235
I'm trying to save PDF file with NSView
objects.
Here is implementation of Square
class (subclass of NSView
).
@implementation Square
- (id)initWithColor:(NSColor *)aColor;
{
if (self = [super init])
{
self.frame = NSMakeRect(0, 0, 50, 50);
self.color = aColor;
}
return self;
}
- (void)drawRect:(NSRect)dirtyRect
{
[self.color set];
NSRectFill(dirtyRect);
}
Here is part of implementation of my DrawView
- sublcass of NSView
- (void)awakeFromNib
{
squareGroup = [[NSMutableArray alloc] init];
}
- (void)addSquare:(Square *)square
{
[squareGroup addObject:square];
[self addSubview:square];
}
- (void)drawRect:(NSRect)dirtyRect
{
[[NSColor whiteColor] set];
NSRectFill(dirtyRect);
}
I can click on button Red
or Blue
and add Square
object with blue or red color and when i clicked Save
i want to save White DrawView
with Square
objects on it. I can move Square
objects on DrawView
now so every single Square
objects are on different places.
My saving method look like below (in DrawView
class):
- (void)saveAsPDF
{
NSString *homeDirectory = NSHomeDirectory();
NSURL *fileURL = [NSURL fileURLWithPath:[homeDirectory stringByAppendingPathComponent:@"file.pdf"]];
CGRect mediaBox = self.bounds;
CGContextRef ctx = CGPDFContextCreateWithURL((__bridge CFURLRef)(fileURL), &mediaBox, NULL);
CGPDFContextBeginPage(ctx, NULL);
for (Square *square in squareGroup) {
[square.layer renderInContext:ctx];
}
[self.layer renderInContext:ctx];
CGPDFContextEndPage(ctx);
CFRelease(ctx);
}
In result i've got only blank file in home directory.
What is wrong with my save method? How can i do it correclty?
Upvotes: 1
Views: 1426
Reputation: 28553
there is a very helpful tutorial here that may help you
they suggest two ways: the first is this, but the second one is more comprehensive and is well worth a look.
(void)didEnd:(NSSavePanel *)sheet
returnCode:(int)code
saveFormat:(void *)saveType
{
if (code == NSOKButton)
{
if (pageIt)
{
}
else
{
NSRect r = [textView bounds];
NSData *data = [textView dataWithPDFInsideRect:r];
[data writeToFile:[sheet filename] atomically:YES];
}
}
}
Upvotes: 2