开发者

Objective C -- How do I format ESC/POS commands?

Below is some sample code showing ESC/POS commands from Epson, and unfortunately I'm a newbie with respect to character formatting and objective c.

PRINT #1, CHR$(&H1B);"@";
PRINT #1, CHR$(&H1B);"a";CHR$(1);
PRINT #1, CHR$(&H1B);"!";CHR$(0);
PRINT #1, CHR$(&H1B);"J";CHR$(4);
PRINT #1, “January 14, 1998 15:00”;
PRINT #1, CHR$(&H1B);"d";CHR$(3);
PRINT #1, CHR$(&H1B);"a";CHR$(0);
PRINT #1, CHR$(&H1B);"!";CHR$(1);
PRINT #1, "TM-U200B $20.00";CHR$(&HA);
PRINT #1, "TM-U200D $21.00";CHR$(&HA);
PRINT #1, "PS-170 $17.00";CHR$(&HA);
PRINT #1, CHR$(&HA);
PRINT #1, CHR$(&H1B);”!”;CHR$(17);
PRINT #1, CHR$(&H1B);”U”;CHR$(1);
PRINT #1, "TOTAL $58.00";CHR$(&HA);
PRINT #1, CHR$(&H1B);"U";CHR$(0);
PRINT #1, CHR$(&H1B);”!”;CHR$(0);
PRINT #1, "------------------------------";CHR$(&HA);
PRINT #1, "PAID $60.00";CHR$(&HA);
PRINT #1,开发者_StackOverflow社区 "CHANGE $ 2.00";CHR$(&HA);
PRINT #1, CHR$(&H1D);"V";CHR$(66);CHR$(0);
END

Anyone know how I would convert the above into a NSData format (either in a single NSData object or multiple NSData objects)? Any guidance is greatly appreciated.


I would recommend creating a formatter class that keeps an NSMutableData object representing the bytes that are to be sent to the printer. For instance,

// EpsonFormatter.h
#import <Foundation/Foundation.h>

@interface EpsonFormatter : NSObject {
    NSMutableData *_data;
}

@property (readonly) NSMutableData *data;

- (void)initializePrinter;
- (void)selectCenterJustification;
- (void)selectStandardPrinterMode;
- (void)appendString:(NSString *)string;
@end

// EpsonFormatter.m
#import "EpsonFormatter.h"

@implementation EpsonFormatter

#define EpsonFormatterESCString "\x1b"

@synthesize data = _data;

- (id)init {
    self = [super init];
    if (self) {
        _data = [[NSMutableData alloc] init];
    }
    return self;
}

- (void)dealloc {
    [_data release];
    [super dealloc];
}

- (void)initializePrinter {
    [_data appendBytes:EpsonFormatterESCString "@" length:2];
}

- (void)selectCenterJustification {
    [_data appendBytes:EpsonFormatterESCString "a" "\x1" length:3];
}

- (void)selectStandardPrinterMode {
    [_data appendBytes:EpsonFormatterESCString "!" "\x0" length:3];
}

- (void)appendString:(NSString *)string {
    [_data appendData:[string dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES]];
}

@end

You would use this class like this:

#import "EpsonFormatter.h"
EpsonFormatter *epsonFormatter = [[[EpsonFormatter alloc] init] autorelease];
[epsonFormatter initializePrinter];
[epsonFormatter selectCenterJustification];
[epsonFormatter selectStandardPrinterMode];
[epsonFormatter appendString:@"January 14, 1998 15:00"];
// …

// In order to obtain the underlying NSData object:
NSData *outputData = epsonFormatter.data;
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜