drawAtPoint不适用于PDF OS X.

时间:2016-03-15 16:39:41

标签: objective-c macos pdf

CGContextShowTextAtPoint表示它已被弃用,因此我想找到一种替代方法,用于将文本绘制到PDF上下文中。以下工作(我想要更改的代码):

CGPDFContextBeginPage(self.writeContext, pageDictionary);

 //Add text
 CGContextSelectFont(self.writeContext, "Helvetica", 26, kCGEncodingMacRoman);
 CGContextSetTextDrawingMode(self.writeContext, kCGTextFill);
 CGContextSetRGBFillColor(self.writeContext, 0, 0, 0, 1);
 const char *text="Hello Text Test";
 CGContextShowTextAtPoint(self.writeContext, 110, 0, text, strlen(text));

 CGPDFContextEndPage(self.writeContext);

但是这段代码不起作用(页面最后只是空白)

CGPDFContextBeginPage(self.writeContext, pageDictionary);

 //Add text
[@"Hello Text Test" drawAtPoint:CGPointMake(100, 100) withAttributes:@{NSFontAttributeName:[NSFont fontWithName:@"Helvetica" size:24]}];
 //=========

CGPDFContextEndPage(self.writeContext);

1 个答案:

答案 0 :(得分:0)

我认为你错过了NSGraphicsContext

下面的完整代码段:

NSLog(@"Print PDF");
CFURLRef filePath;
NSSavePanel*    panel = [NSSavePanel savePanel];
[panel setNameFieldStringValue:[self.selectedAccount.name stringByAppendingString:@".pdf"]];
[panel beginSheetModalForWindow:self.window completionHandler:^(NSInteger result){
    if (result == NSFileHandlingPanelOKButton) {

        NSURL*  theFile = [panel URL];
        CGRect mediaBox = CGRectMake(0, 0, 576.0, 576.0);
        CFURLRef saveLocation = CFBridgingRetain(theFile);
        //dictionary to store doc attributes
        CFMutableDictionaryRef attributes = CFDictionaryCreateMutable(NULL,
                                                                      3,
                                                                      &kCFTypeDictionaryKeyCallBacks,
                                                                      &kCFTypeDictionaryValueCallBacks);

        CFDictionaryAddValue(attributes, kCGPDFContextAuthor, CFSTR("Rich Claxton"));
        CFDictionaryAddValue(attributes, kCGPDFContextTitle, CFSTR("This is working"));

        CGContextRef pdfContext = CGPDFContextCreateWithURL(saveLocation, &mediaBox, attributes);

        /** Create NSGraphicsContext !! **/
        NSGraphicsContext* newGC = [NSGraphicsContext graphicsContextWithGraphicsPort:pdfContext flipped:NO];
        [NSGraphicsContext saveGraphicsState];
        [NSGraphicsContext setCurrentContext:newGC];


        CGPDFContextBeginPage(pdfContext, NULL);

        //Draw Strings here
        [@"Hello World !!" drawAtPoint:CGPointMake(2.0,2.0) withAttributes:(NULL)];

        CGPDFContextEndPage(pdfContext);
        CGPDFContextClose(pdfContext);
        CGContextRelease(pdfContext);
    }
}];