需要使用 obj-c 打印自定义 Header

Need to Print a Custom Header using obj-c

我正在创建一个 NSView,它使用这段代码可以正常打印:

NSPrintInfo *printInfo = [NSPrintInfo sharedPrintInfo];
[printInfo setHorizontalPagination:NSFitPagination];
[printInfo setHorizontallyCentered:YES];
[printInfo setVerticallyCentered:YES];
NSPrintOperation *operation = [NSPrintOperation printOperationWithView:printView printInfo:printInfo];

NSPrintPanel *printerPanel = operation.printPanel;

printerPanel.options = NSPrintPanelShowsPaperSize | NSPrintPanelShowsPageRange | NSPrintPanelShowsOrientation | NSPrintPanelShowsPageSetupAccessory | NSPrintPanelShowsPreview;

[operation runOperationModalForWindow:window delegate:nil
                       didRunSelector:nil contextInfo:nil];

我在 applicationDidFinishLaunching 中也有这段代码

NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setValue:@YES forKey:NSPrintHeaderAndFooter];

现在,如果我尝试覆盖这些方法

 - (void)drawPageBorderWithSize:(NSSize)pageSize
 - (NSAttributedString *)pageHeader

他们甚至没有接到电话。有人知道为什么吗?

为了覆盖 NSView 的方法,您首先必须子 class 文件,然后将覆盖的方法放在新的自定义 class 中。实例化并使用您的 subclass 而不是 NSView 并记住在覆盖的方法中进行 super 调用,以便一切按预期工作。其他的应该不会太多吧,如果你已经有了sub-class你可以post它,我可以看看。

实际上我这样做了:对于我的 .xib 中的多行标签,我在检查器

中添加了自定义 class

然后我有这个 .h 和 .m 文件 - 它适用于文本但不适用于图像

NSTextFieldForPrint.h :

#import <Cocoa/Cocoa.h>
@interface NSTextFieldForPrint : NSTextField
@end

NSTextFieldForPrint.m

#import "NSTextFieldForPrint.h"
@implementation NSTextFieldForPrint
- (NSAttributedString *)pageHeader
{
    NSLog(@"Am i called?");
    NSAttributedString *theHeader = nil;
    NSString *myImagePath = [[[NSBundle mainBundle] resourcePath]  stringByAppendingString:@"header.jpg"];
    NSImage *pic = [[NSImage alloc] initWithContentsOfFile:myImagePath];
    NSTextAttachmentCell *attachmentCell = [[NSTextAttachmentCell alloc] initImageCell:pic];
    NSTextAttachment *attachment = [[NSTextAttachment alloc] init];
    [attachment setAttachmentCell: attachmentCell ];
    theHeader = [NSAttributedString  attributedStringWithAttachment: attachment];
    return theHeader;

    //return [[NSAttributedString alloc] initWithString:@"adsfasdf"];
}

@end